package com.dmc.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.excel.EasyExcel;
import com.dmc.conf.Constant;
import com.dmc.conf.ExcelListener;
import com.dmc.dict.*;
import com.dmc.entity.Message;
import com.dmc.entity.UserAuthenticate;
import com.dmc.mapper.*;
import com.dmc.model.*;
import com.dmc.service.DistributionService;
import com.dmc.service.UserAccountService;
import com.dmc.service.UserService;
import com.dmc.util.DecimalUtil;
import com.dmc.util.id.IdUtil;
import com.dmc.util.util.OrderCodeUtil;
import com.dmc.util.util.SessionUtil;
import com.dmc.util.util.StringUtil;
import com.dmc.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.IdGenerator;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
@Slf4j
public class DistributionServiceImpl implements DistributionService, InitializingBean {

    private static volatile boolean taskSwith = true;

    @Autowired
    private DistributionGoodsMapper distributionGoodsMapper;

    @Autowired
    private DistributionShareRelationMapper distributionShareRelationMapper;

    @Autowired
    private DistributionHelpRelationMapper distributionHelpRelationMapper;

    @Autowired
    private DistributionProcotolMapper distributionProcotolMapper;

    @Autowired
    private DistributionOrderMapper distributionOrderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DistributionOrderGoodsMapper distributionOrderGoodsMapper;

    @Autowired
    private DistributionOrderQueueMapper distributionOrderQueueMapper;

    @Resource
    private IntegralTransactionMapper integralTransactionMapper;

    @Resource
    private TUserAccountMapper tUserAccountMapper;

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private BenefitTransactionMapper benefitTransactionMapper;

    @Autowired
    private UserAuthenticateMapper userAuthenticateMapper;

    @Resource
    private UserService userService;

    @Resource
    private DistributionOrderQueueGoodsMapper distributionOrderQueueGoodsMapper;

    @Autowired
    private PaymentMapper paymentMapper;

    @Resource
    private DistributionTwoLevelCountMapper distributionTwoLevelCountMapper;

    @Autowired
    private DistributionTwoLevelCountRecordMapper distributionTwoLevelCountRecordMapper;

    @Autowired
    private DistributionTwoLevelHelpRecordMapper distributionTwoLevelHelpRecordMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private PlatformBankCardMapper platformBankCardMapper;

    @Autowired
    private DistributionBonusUserRecordMapper distributionBonusUserRecordMapper;

    @Autowired
    private DistributionGoodsPackageMapper distributionGoodsPackageMapper;

    @Autowired
    private DistributionPackageGoodsMapper distributionPackageGoodsMapper;

    @Autowired
    private DistributionPackageOrderMapper distributionPackageOrderMapper;

    @Autowired
    private DistributionPackageOrderGoodsMapper distributionPackageOrderGoodsMapper;

    @Autowired
    private VipConfigMapper vipConfigMapper;

    @Autowired
    private AchievementBonusConfigDetailMapper achievementBonusConfigDetailMapper;

    @Autowired
    private AchievementBonusConfigMapper achievementBonusConfigMapper;

    @Override
    public void saveGoods(DistributionGoodsVo vo) {
        String levelFlag = vo.getLevelFlag();
        if(StringUtils.isBlank(levelFlag)){
            levelFlag = Constant.ZHONG_JI_DISTRIBUTION_FLAG;
            vo.setLevelFlag(levelFlag);
        }
        //查询是否有同名的分销商
        Map<String,Object> params = new HashMap<>();
        params.put("level_flag",levelFlag);
        params.put("status",1);
        List<DistributionGoods> distributionGoods = distributionGoodsMapper.selectByMap(params);
        Assert.isTrue(CollectionUtils.isEmpty(distributionGoods),"添加失败,已有同级别商品");
        String distributionName = vo.getDistributionName();
        //查询是否有同名的分销商
        params.clear();
        params.put("distribution_name",distributionName);
        params.put("status",1);
        distributionGoods = distributionGoodsMapper.selectByMap(params);
        Assert.isTrue(CollectionUtils.isEmpty(distributionGoods),"添加失败,已有同名商品");
        DistributionGoods goods = new DistributionGoods();
        BeanUtil.copyProperties(vo,goods, CopyOptions.create().setIgnoreNullValue(true));
        goods.setStatus(1);
        goods.setCreateTime(new Date());
        distributionGoodsMapper.insert(goods);
    }

    @Override
    public void updateGoods(DistributionGoodsVo vo) {
        Long id = vo.getId();
        Assert.notNull(id,"参数错误,请传输ID");
        DistributionGoods distributionGoods = distributionGoodsMapper.selectById(id);
        Assert.notNull(id,"参数错误,无此商品");
        Integer status = vo.getStatus();
        if(status!=null && status==1){
            String distributionName = vo.getDistributionName();
            Map<String,Object> params = new HashMap<>();
            params.put("distribution_name",distributionName);
            params.put("status",1);
            List<DistributionGoods> goosList = distributionGoodsMapper.selectByMap(params);
            if(CollectionUtils.isEmpty(goosList)){
                for (DistributionGoods goods : goosList) {
                    Integer status1 = goods.getStatus();
                    Assert.isTrue(status!=null && status==1 && id!=goods.getId(),"修改失败,已有同名商品");
                }
            }
        }
        DistributionGoods goods = new DistributionGoods();
        BeanUtil.copyProperties(vo,goods, CopyOptions.create().setIgnoreNullValue(true));
        distributionGoodsMapper.updateById(goods);
    }

    @Override
    public DataTable<DistributionGoodsVo> getDistributionGoodsList(DistributionGoodsVo vo) {
        //PageHelper.startPage(vo.getStart(), vo.getLength());
        Integer goodsType = vo.getGoodsType();
        List<DistributionGoodsVo> result = new ArrayList<>();
        if(goodsType == null || goodsType == 0){
            List<DistributionGoodsVo> goosList = distributionGoodsMapper.getDistributionGoodsList(vo);
            if(CollectionUtil.isNotEmpty(goosList)){
                for (DistributionGoodsVo goodsVo : goosList) {
                    goodsVo.setGoodsType(0);
                    result.add(goodsVo);
                }
            }
        }
        if(goodsType == null || goodsType == 1){
            //获取套餐包
            Map<String,Object> params = new HashMap<>();
            params.put("status",1);
            List<DistributionGoodsPackage> packageList = distributionGoodsPackageMapper.selectByMap(params);
            if(CollectionUtil.isNotEmpty(packageList)){
                for (DistributionGoodsPackage distributionGoodsPackage : packageList) {
                    DistributionGoodsVo goodsVo = new DistributionGoodsVo();
                    goodsVo.setId(distributionGoodsPackage.getId());
                    goodsVo.setGoodsType(1);
                    goodsVo.setDistributionName(distributionGoodsPackage.getPackageName());
                    goodsVo.setPrice(distributionGoodsPackage.getPrice());
                    goodsVo.setBuyLimit(distributionGoodsPackage.getBuyLimit());
                    goodsVo.setDes(distributionGoodsPackage.getDes());
                    //获取分销商品详情
                    params.clear();
                    params.put("package_id",distributionGoodsPackage.getId());
                    List<DistributionPackageGoods> packageGoodList = distributionPackageGoodsMapper.selectByMap(params);
                    if(CollectionUtil.isNotEmpty(packageGoodList)){
                        goodsVo.setPackageGoodList(packageGoodList);
                        result.add(goodsVo);
                    }
                }
            }
        }
        DataTable<DistributionGoodsVo> tables = new DataTable<>();
        int size = result.size();
        tables.setRecordsTotal((long)size);
        tables.setRecordsFiltered((long)size);
        tables.setDraw(vo.getDraw());
        tables.setData(result);
        return tables;
    }

    @Override
    public DataTable<DistributionShareRelationVo> getShareRelation(Integer shareLevel) {
        Long currUid = SessionUtil.getCurrUid();
        List<DistributionShareRelationVo> list = new ArrayList<>();
        getShareRelationForLevel(list,currUid,currUid,shareLevel,shareLevel);
        DataTable<DistributionShareRelationVo> tables = new DataTable<>();
        tables.setData(list);
        //获取自己的分享人
        DistributionShareRelation shareQuery = new DistributionShareRelation();
        shareQuery.setUserId(currUid);
        shareQuery = distributionShareRelationMapper.selectOne(shareQuery);
        if(shareQuery !=null){
            Long shareUserId = shareQuery.getShareUserId();
            User byId = userMapper.getById(shareUserId);
            DistributionShareRelationVo vo = new DistributionShareRelationVo();
            vo.setUserName(byId.getUsername());
            vo.setUserPhoto(byId.getUserPhoto());
            vo.setCreateTime(shareQuery.getCreateTime());
            tables.setOtherData(vo);
        }
        return tables;
    }

    /**
     * 递归获取分销用户
     * @param reslut
     * @param currUid
     * @param shareLevel 获取当前等级的用户
     */
    private void getShareRelationForLevel(List<DistributionShareRelationVo> reslut,Long currUid,Long currUidQuery,int shareLevel,int initLevel){
        List<DistributionShareRelationVo> list = distributionShareRelationMapper.getShareRelation(currUidQuery);
        List<Long> userIdList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for (DistributionShareRelationVo distributionShareRelationVo : list) {
                Long userId = distributionShareRelationVo.getUserId();
                userIdList.add(userId);
                if(shareLevel == 1){

                    Integer level = distributionShareRelationVo.getLevel();
                    if(level>1){
                        distributionShareRelationVo.setLevelName("分销会员");
                    }else{
                        String descByCn = UserLevelDict.getDescByCn(level);
                        distributionShareRelationVo.setLevelName(descByCn);
                    }
                    reslut.add(distributionShareRelationVo);
                    //获取分销订单数量
                    Integer orderNum = distributionOrderMapper.getOrderNumByUserId(userId, null);
                    distributionShareRelationVo.setDistributionOrderNum(orderNum);
                }
            }
        }
        shareLevel--;
        if(shareLevel > 0){
            if(!CollectionUtils.isEmpty(list)){
                for (Long userId : userIdList) {
                    if(initLevel==2 && userId.equals(currUid)){
                        continue;
                    }
                    getShareRelationForLevel(reslut,currUid,userId,shareLevel,initLevel);
                }
            }
        }
    }

    @Override
    public DataTable<DistributionHelpRelationVo> getHelpRelation(Integer type) {
        Long currUid = SessionUtil.getCurrUid();
        List<DistributionHelpRelationVo> list = distributionHelpRelationMapper.getHelpRelation(currUid,type,null,null);
        if(!CollectionUtils.isEmpty(list)){
            for (DistributionHelpRelationVo relationVo : list) {
                Integer level = relationVo.getLevel();
                String descByCn = UserLevelDict.getDescByCn(level);
                relationVo.setLevelName(descByCn);
            }
        }
        DataTable<DistributionHelpRelationVo> tables = new DataTable<>();
        tables.setData(list);
        return tables;
    }

    @Override
    public DistributionProcotolVo getProtol() {
        Map<String,Object> params = new HashMap<>();
        params.put("status",1);
        List<DistributionProcotol> distributionProcotols = distributionProcotolMapper.selectByMap(params);
        DistributionProcotolVo vo = null;
        if(!CollectionUtils.isEmpty(distributionProcotols)){
            vo = new DistributionProcotolVo();
            BeanUtil.copyProperties(distributionProcotols.get(0),vo);
        }
        return vo;
    }

    @Override
    public DataTable<DistributionProcotolVo> getProtolList(DistributionProcotolVo vo) {
        PageHelper.startPage(vo.getStart(), vo.getLength());
        List<DistributionProcotolVo> list = distributionProcotolMapper.getProtolList(vo);
        DataTable<DistributionProcotolVo> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) list).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(vo.getDraw());
        tables.setData(list);
        return tables;
    }

    @Override
    public void saveOrUpdateProcotol(DistributionProcotolVo vo) {
        Long id = vo.getId();
        if(vo.getStatus() == 1){
            DistributionProcotolVo protol = getProtol();
            if(protol!=null){
                if(id!=null){
                    Long proId = protol.getId();
                    Assert.isTrue(proId.equals(id),"更新失败,已经有有效协议");
                }else{
                    Assert.isNull(protol,"插入失败,已经有有效协议");
                }
            }
        }
        if(id == null){
            DistributionProcotol pro = new DistributionProcotol();
            BeanUtil.copyProperties(vo,pro);
            pro.setStatus(1);
            pro.setCreateTime(new Date());
            distributionProcotolMapper.insert(pro);
        }else{
            DistributionProcotol distributionProcotol = distributionProcotolMapper.selectById(id);
            Assert.notNull(distributionProcotol,"更新失败,无此协议");
            BeanUtil.copyProperties(vo,distributionProcotol, CopyOptions.create().setIgnoreNullValue(true));
            distributionProcotolMapper.updateById(distributionProcotol);
        }
    }

    /**
     * 购买分销商前置校验
     */
    private User checkAuth(Long currUid,Boolean isAuth){
        if(currUid == null){
            currUid = SessionUtil.getCurrUid();
        }
        User byId = userMapper.getUserById(currUid);
        Integer level = byId.getLevel();
        Assert.isTrue(level!=null && level>0 ,"非会员无法购买分销商产品");
        //判断是否已经认证身
        if(isAuth){
            UserAuthenticate userAuthenticateByUserId = userAuthenticateMapper.getUserAuthenticateByUserId(currUid);
            Assert.isTrue(userAuthenticateByUserId!=null && userAuthenticateByUserId.getStatus()==1 ,"未进行身份认证,无法购买分销商产品");
        }
        return byId;
    }

    @Override
    public DistributionOrderVo addDistributionOrder(DistributionOrderVo vo,Boolean isAuth) {
        User byId = checkAuth(vo.getUserId(), isAuth);
        long currUid = byId.getId();
        //获取当前人用户信息
        vo.setShareUserId(byId.getShareUserId());
        vo.setUserId(currUid);
        vo.setOrderNo(OrderCodeUtil.getDistributionCode(currUid));
        vo.setOrderStatus(DistributionStatusDict.ORDER_STATUS_CREATED.getCn());
        //获取当前分销商品信息
        Long distributionGoodsId = vo.getDistributionGoodsId();
        Assert.notNull(distributionGoodsId,"参数错误,请传输分销商品ID");
        DistributionGoods distributionGoods = distributionGoodsMapper.selectById(distributionGoodsId);
        Assert.notNull(distributionGoods,"参数错误,无此分销商品");
        Integer payType = vo.getPayType();
        if(DistriButionPayTypeDict.checkFhType(payType)){
            //如果是分红购买,则不赠送积分
            vo.setBonusPoints(BigDecimal.ZERO);
            vo.setPrice(distributionGoods.getPromotedPresentationAdd());
        }else{
            vo.setBonusPoints(distributionGoods.getBonusPoints());
            BigDecimal priceorder = vo.getPrice();
            if(priceorder == null){
                vo.setPrice(distributionGoods.getPrice());
            }
        }
        TUserAccount tUserAccount = null;
        BigDecimal benefitNew = null;
        if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_6.getCn()){
            //如果是线下支付需要传输转账号码
            PlatformBankCard platformBankCard = new PlatformBankCard();
            platformBankCard.setStop(0);
            platformBankCard = platformBankCardMapper.selectOne(platformBankCard);
            Assert.notNull(platformBankCard,"没有配置平台转账号码");
            vo.setPlatformId(platformBankCard.getId());
            vo.setPlatformBankId(platformBankCard.getBankId());
            vo.setBankNum(platformBankCard.getBankNum());
            vo.setBankName(platformBankCard.getBankName());
            vo.setBankUserName(platformBankCard.getBankUserName());
        }else if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn()){
            //如果是收益金支付,则判断收益是否足以支付
            tUserAccount = userAccountService.initUserAccountByUserId(currUid);
            BigDecimal benefit = tUserAccount.getBenefit();
            benefitNew = DecimalUtil.subArrayOriginalValue(benefit, vo.getPrice());
            Assert.isTrue(benefitNew.compareTo(BigDecimal.ZERO)>=0,"收益金额不足,请选择其他支付方式");
        }
        vo.setBonusPresentation(distributionGoods.getBonusPresentation());
        DistributionOrder order = new DistributionOrder();
        BeanUtil.copyProperties(vo,order);
        order.setCreateTime(new Date());
        distributionOrderMapper.insert(order);
        DistributionOrderGoods orderGoods = new DistributionOrderGoods();
        BeanUtil.copyProperties(distributionGoods,orderGoods);
        orderGoods.setOrderId(order.getId());
        if(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn() == order.getOrderType()){
            orderGoods.setPrice(order.getPrice());
        }
        distributionOrderGoodsMapper.insert(orderGoods);
        DistributionOrderGoodsVo goodsVo = new DistributionOrderGoodsVo();
        BeanUtil.copyProperties(orderGoods,goodsVo);
        vo.setId(order.getId());
        vo.setDistributionOrderGoodsVo(goodsVo);
        if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn() &&
                DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn() != order.getOrderType()){
            //如果是收益金支付,则直接完成首款
            tUserAccount.setBenefit(benefitNew);
            tUserAccountMapper.updateById(tUserAccount);
            BenefitTransaction bt = new BenefitTransaction( currUid,currUid,order.getId(),benefitNew,
                    BenefitTranTypeDict.BENEFIT_TRAN_TYPE_1000.getCn(),  distributionGoods.getPrice().negate(), "购买分销商");
            userAccountService.addBenefitTransaction(bt);
            postProcess(order.getId(),DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn(),false,false);
        }
        return vo;
    }

    @Override
    public DataTable<DistributionOrderVo> getDistributionOrderList(DistributionOrderVo vo) {
        PageHelper.startPage(vo.getStart(), vo.getLength());
        String userName = vo.getUserName();
        if(StringUtils.isNotBlank(userName)){
            vo.setUserName("%"+userName.trim()+"%");
        }
        String orderNo = vo.getOrderNo();
        if(StringUtils.isNotBlank(orderNo)){
            vo.setOrderNo("%"+orderNo.trim()+"%");
        }
        String distributionName = vo.getDistributionName();
        if(StringUtils.isNotBlank(distributionName)){
            vo.setDistributionName("%"+distributionName.trim()+"%");
        }
        List<DistributionOrderVo> list = distributionOrderMapper.getDistributionOrderList(vo);
        if(!CollectionUtils.isEmpty(list)){
            for (DistributionOrderVo distributionOrderVo : list) {
                Integer orderType = distributionOrderVo.getOrderType();
                if(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn() == orderType){
                    Long distributionGoodsId = distributionOrderVo.getDistributionGoodsId();
                    DistributionGoodsPackage distributionGoodsPackage = distributionGoodsPackageMapper.selectById(distributionGoodsId);
                    distributionOrderVo.setDistributionName(distributionGoodsPackage.getPackageName());
                    //套餐包的处理
                    Map<String,Object> param = new HashMap<>();
                    param.put("p_id",distributionOrderVo.getId());
                    param.put("order_type",DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn());
                    List<DistributionOrder> distributionOrders = distributionOrderMapper.selectByMap(param);
                    List<DistributionOrderVo> packSubOrderList = new ArrayList<>();
                    if(CollectionUtil.isNotEmpty(distributionOrders)){
                        for (DistributionOrder distributionOrder : distributionOrders) {
                            DistributionOrderVo voQuery = new DistributionOrderVo();
                            voQuery.setId(distributionOrder.getId());
                            List<DistributionOrderVo> distributionOrderList = distributionOrderMapper.getDistributionOrderList(voQuery);
                            packSubOrderList.addAll(distributionOrderList);
                        }
                    }
                    distributionOrderVo.setPackSubOrderList(packSubOrderList);
                }else{
                    Long distributionQueueGoodsId = distributionOrderVo.getDistributionQueueGoodsId();
                    DistributionGoods distributionOrderGood = distributionGoodsMapper.selectById(distributionQueueGoodsId);
                    distributionOrderVo.setCurrentLevelBonusPoints(distributionOrderGood.getBonusPoints());
                    distributionOrderVo.setCurrentLevelBonusPresentation(distributionOrderGood.getBonusPresentation());
                    DistributionOrderGoodsVo goodVo = new DistributionOrderGoodsVo();
                    BeanUtil.copyProperties(distributionOrderGood,goodVo);
                    distributionOrderVo.setDistributionOrderGoodsVo(goodVo);
                    Integer payType = distributionOrderVo.getPayType();
                    if(DistriButionPayTypeDict.checkFhType(payType)){
                        goodVo.setPrice(goodVo.getPromotedPresentationAdd());
                        distributionOrderVo.setBonusPoints(BigDecimal.ZERO);
                        distributionOrderVo.setCurrentLevelBonusPoints(BigDecimal.ZERO);
                    }
                    if(StringUtils.isBlank(distributionOrderVo.getDistributionName())){
                        distributionOrderVo.setDistributionName(distributionOrderGood.getDistributionName());
                    }
                    Integer orderStatus = distributionOrderVo.getOrderStatus();
                    if(DistributionStatusDict.ORDER_STATUS_PAIED.getCn() == orderStatus){
                        String levelFlag = distributionOrderGood.getLevelFlag();
                        Integer vipOrders = distributionOrderVo.getVipOrders();
                        Long sort = distributionOrderVo.getRealSort();
                        int rank = distributionOrderQueueMapper.getRank(sort,levelFlag,vipOrders);
                        distributionOrderVo.setRank(++rank);
                    }
                    distributionOrderVo.setProgress(getOrderProcess(distributionOrderVo.getLevelFlagInit(),distributionOrderVo.getLevelFlagQueue(),DistributionStatusDict.ORDER_STATUS_CLOSE.getCn() == orderStatus));
                    if(DistriButionPayTypeDict.checkCashPayType(payType)){
                        distributionOrderVo.setPayTypeName("购买");
                        distributionOrderVo.setPayMoney(distributionOrderGood.getPrice());
                        Long pId = distributionOrderVo.getPId();
                        if(pId !=null){
                            DistributionOrder distributionOrder = distributionOrderMapper.selectById(pId);
                            if(distributionOrder.getOrderNo().contains("FXP")){
                                distributionOrderVo.setPackageOrderNo(distributionOrder.getOrderNo());
                            }
                        }
                    }else{
                        Long pId = distributionOrderVo.getPId();
                        if(pId !=null){
                            DistributionOrder distributionOrder = distributionOrderMapper.selectById(pId);
                            distributionOrderVo.setPayTypeName(distributionOrder.getOrderNo()+DistriButionPayTypeDict.getDescByCn(payType));
                        }
                    }
                    String levelFlagInit = distributionOrderVo.getLevelFlagInit();
                    DistributionOrderQueueGoods dis = new DistributionOrderQueueGoods();
                    dis.setOrderId(distributionOrderVo.getId());
                    dis.setLevelFlag(levelFlagInit);
                    DistributionOrderQueueGoods distributionOrderQueueGoods = distributionOrderQueueGoodsMapper.selectOne(dis);
                    if(distributionOrderQueueGoods!=null){
                        distributionOrderVo.setSettleTime(distributionOrderQueueGoods.getCreateTime());
                    }
                }

                //查看是否有推荐奖
                BenefitTransaction benefitQuery = new BenefitTransaction();
                benefitQuery.setOrderId(distributionOrderVo.getId());
                benefitQuery.setType(BenefitTranTypeDict.BENEFIT_TRAN_TYPE_200.getCn());
                BenefitTransaction benefitTransaction = benefitTransactionMapper.selectOne(benefitQuery);
                if(benefitTransaction!=null){
                    distributionOrderVo.setRecommendAward(benefitTransaction.getBenefit());
                }
            }
        }
        DataTable<DistributionOrderVo> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) list).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(vo.getDraw());
        tables.setData(list);
        return tables;
    }

    @Override
    public void packAgePostProcess(Long orderId, Integer payType, Boolean isZero, boolean update) {
        DistributionOrder distributionOrder = distributionOrderMapper.selectById(orderId);
        distributionOrder.setOrderStatus(DistributionStatusDict.ORDER_STATUS_PAIED.getCn());
        distributionOrderMapper.updateById(distributionOrder);
        User byId = userMapper.getById(distributionOrder.getUserId());
        BigDecimal distributionTotalPrice = byId.getDistributionTotalPrice();
        distributionTotalPrice = DecimalUtil.addArray(distributionTotalPrice,distributionOrder.getPrice());
        byId.setDistributionTotalPrice(distributionTotalPrice);
        userMapper.update(byId);
        Map<String,Object> param = new HashMap<>();
        param.put("p_id",distributionOrder.getId());
        param.put("order_type",DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn());
        List<DistributionOrder> distributionOrders = distributionOrderMapper.selectByMap(param);
        if(CollectionUtil.isNotEmpty(distributionOrders)){
            String firstLevelInit = Constant.ZHONG_JI_DISTRIBUTION_FLAG;
            for (DistributionOrder order : distributionOrders) {
                DistributionGoods distributionGoods = distributionGoodsMapper.selectById(order.getDistributionGoodsId());
                String levelFlag = distributionGoods.getLevelFlag();
                if(Constant.GAO_JI_DISTRIBUTION_FLAG.equals(levelFlag)){
                    firstLevelInit = Constant.GAO_JI_DISTRIBUTION_FLAG;
                }
            }
            //维护首单标识
            String firstLevelFlag = byId.getFirstLevelFlag();
            if(StringUtils.isBlank(firstLevelFlag) || "0".equals(firstLevelFlag)){
                byId.setFirstLevelFlag(firstLevelInit);
            }
            for (DistributionOrder order : distributionOrders) {
                postProcess(order.getId(),DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn(),false,false);
            }

        }

    }

    /**
     * 荣誉身份业绩的累积
     */
    private void achievementUpdate(BigDecimal price,User byId){
        Long userId = byId.getId();
        Integer vipLevel = byId.getVipLevel();
        VipConfig vipConfig = vipConfigMapper.selectCurr(vipLevel);
        if(vipConfig == null){
            return;
        }
        Integer distributionUserLevel = vipConfig.getDistributionUserLevel();
        Integer distributionUserNum = vipConfig.getDistributionUserNum();
        int num = userMapper.selectShareUserNumByLevel(userId,distributionUserLevel);
        if(num >= distributionUserNum){
            accumulationAchievement( price, byId, vipLevel);
        }
        //如果分销商数量大于配置数量则维护业绩
        Long userIdEmp = userId;
        Long shareUserIdEmp = byId.getShareUserId();
        while(shareUserIdEmp!=null && !shareUserIdEmp.equals(userIdEmp)){
            User shareUser= userMapper.getById(shareUserIdEmp);
            accumulationAchievement( price, shareUser, shareUser.getVipLevel());
            userIdEmp = shareUserIdEmp;
            shareUserIdEmp = shareUser.getShareUserId();
        }
    }

    /**
     * 获取上架的业绩奖限制
     * @return
     */
    private Map<String,AchievementBonusConfigVo> getAllAchievementBonusConfigMap(){
        Map<String,AchievementBonusConfigVo> result = new HashMap<>();
        Map<String,Object> param = new HashMap<>();
        param.put("status","0");
        param.put("deleted","0");
        List<AchievementBonusConfig> achievementBonusConfigs = achievementBonusConfigMapper.selectByMap(param);
        if(CollectionUtil.isNotEmpty(achievementBonusConfigs)){
            for (AchievementBonusConfig achievementBonusConfig : achievementBonusConfigs) {
                AchievementBonusConfigVo vo = new AchievementBonusConfigVo();
                BeanUtil.copyProperties(achievementBonusConfig,vo);
                result.put(achievementBonusConfig.getLevelFlag(),vo);
                param.clear();
                param.put("deleted",0);
                param.put("config_id",achievementBonusConfig.getId());
                List<AchievementBonusConfigDetail> achievementBonusConfigDetailList = achievementBonusConfigDetailMapper.selectByMap(param);
                List<AchievementBonusConfigDetailVo> detailVoList = new ArrayList<>();
                if(CollectionUtil.isNotEmpty(achievementBonusConfigs)){
                    for (AchievementBonusConfigDetail achievementBonusConfigDetail : achievementBonusConfigDetailList) {
                        AchievementBonusConfigDetailVo detailVo = new AchievementBonusConfigDetailVo();
                        BeanUtil.copyProperties(achievementBonusConfigDetail,detailVo);
                        detailVoList.add(detailVo);
                    }

                }
                vo.setConfigDetailList(detailVoList);
            }
        }
        return result;
    }
    /**
     * 提成的累积
     */
    private void achievementBounsUpdate(User byId, DistributionOrder distributionOrder,String orderLevel, AchievementBonusConfig config){
        List<AchievementBonusConfigDetail> detailList = achievementBonusConfigDetailMapper.selectDetailByConfig(config.getId());
        if(CollectionUtil.isEmpty(detailList)){
            return;
        }
        String levelFlag = config.getLevelFlag();
        int size = detailList.size();
        Integer generationsAccumulation = config.getGenerations();
        BigDecimal achievementLimit = config.getAchievementLimit();
        for (int i = 0; i < size; i++) {
            AchievementBonusConfigDetail achievementBonusConfigDetail = detailList.get(i);
            Integer detailGenerations = achievementBonusConfigDetail.getGenerations();
            User shareUserQuery = byId;
            //获取对应代数的上级
            Long shareUserId = null;
            Long id = byId.getId();
            shareUserId = shareUserId == null || shareUserId.equals(id)?null:shareUserId;
            for (int j = 1; j <= detailGenerations; j++) {
                shareUserId = shareUserQuery.getShareUserId();
                shareUserId = shareUserId == null || shareUserId.equals(shareUserQuery.getId())?null:shareUserId;
                if(shareUserId == null){
                    break;
                }
                shareUserQuery = userMapper.getById(shareUserId);
            }
            if(shareUserId == null){
                //如果没有此代数的上级,则返回
                return;
            }
            if(shareUserQuery == null){
                break;
            }
            String firstLevelFlag = shareUserQuery.getFirstLevelFlag();
            if(!levelFlag.equals(firstLevelFlag)){
                continue;
            }
            int sharenumOne = userMapper.getDistributionShareNum(shareUserId);
            if(sharenumOne<3){
                continue;
            }
            BigDecimal distributionTotalPriceAll = getNextAchievement(shareUserId, shareUserQuery.getDistributionTotalPrice(), generationsAccumulation);
            boolean isBouns = distributionTotalPriceAll.compareTo(achievementLimit)>=0;
            if(isBouns){
                BigDecimal bonus = BigDecimal.ZERO;
                if(Constant.ZHONG_JI_DISTRIBUTION_FLAG.equals(orderLevel)){
                    bonus = achievementBonusConfigDetail.getZhongJiBonus();
                }else if(Constant.GAO_JI_DISTRIBUTION_FLAG.equals(orderLevel)){
                    bonus = achievementBonusConfigDetail.getGaoJiBonus();
                }
                TUserAccount userAccount=userAccountService.initUserAccountByUserId(shareUserId);
                BigDecimal benefit = userAccount.getBenefit();
                BigDecimal benefitNew = DecimalUtil.addArray(benefit, bonus);
                userAccount.setBenefit(benefitNew);
                tUserAccountMapper.updateById(userAccount);
                BenefitTransaction bt = new BenefitTransaction( shareUserId,id,Long.valueOf(distributionOrder.getId()),benefitNew,
                        BenefitTranTypeDict.BENEFIT_TRAN_TYPE_1200.getCn(), bonus,
                        byId.getUsername()+"购买分销商,订单号:"+distributionOrder.getOrderNo()+"获得提成奖励");
                userAccountService.addBenefitTransaction(bt);
            }
        }
    }

    /**
     * 获取下级所有业绩
     * @return
     */
    public BigDecimal getNextAchievement(long userId,BigDecimal achievementAll,Integer generations){
        if(generations==0){
            return achievementAll;
        }
        Map<String,Object> para = new HashMap<>();
        para.put("share_user_Id",userId);
        List<User> list = userMapper.getShareUser(userId);
        generations--;
        if(CollectionUtil.isNotEmpty(list)){
            for (User user : list) {
                Long id = user.getId();
                if(userId == id){
                    //不计算自己
                    continue;
                }
                achievementAll = DecimalUtil.addArray(achievementAll, user.getDistributionTotalPrice());
                achievementAll =  getNextAchievement(user.getId(),achievementAll,generations);
            }
        }
        return achievementAll;
    }

    /**
     * 进行荣誉业绩累加,并校验是否可以升级,如果可以则进行升级
     * @param price
     * @param user
     * @param vipLevel
     */
    private void accumulationAchievement(BigDecimal price,User user,Integer vipLevel){
        Long userId = user.getId();
        TUserAccount userAccount= userAccountService.initUserAccountByUserId(userId);
        BigDecimal achievement = userAccount.getAchievement();
        achievement = DecimalUtil.addArray(achievement, price);
        userAccount.setAchievement(achievement);
        tUserAccountMapper.updateById(userAccount);
        VipConfig vipConfig = vipConfigMapper.selectCurr(vipLevel);
        if(vipConfig == null){
            return;
        }
        Integer vipLevelNew = null;
        while(vipConfig != null){
            Integer distributionUserLevel = vipConfig.getDistributionUserLevel();
            Integer distributionUserNum = vipConfig.getDistributionUserNum();
            BigDecimal achievementUpdate = vipConfig.getAchievement();
            int num = userMapper.selectShareUserNumByLevel(userId,distributionUserLevel);
            if(num >= distributionUserNum && achievement.compareTo(achievementUpdate)>=0){
                //满足晋升条件
                vipLevelNew = vipConfig.getLevel();
                vipConfig = vipConfigMapper.selectFirst(vipLevelNew);
                if(vipConfig == null){
                    break;
                }
            }else{
                break;
            }
        }
        if(vipLevelNew!=null){
            user.setVipLevel(vipLevelNew);
            userMapper.updateById(user);
        }
    }

    /**
     * 业绩相关统计
     * @param price
     * @param userId
     */
    private void achievementCalculation( DistributionOrder distributionOrder,BigDecimal price,Long userId,String levelFlag){
        User byId = userMapper.getById(userId);
        //业绩身份的累积
        achievementUpdate( price, byId);
        //提成的累积
        Map<String,Object> param = new HashMap<>();
        param.put("status","0");
        param.put("deleted","0");
        List<AchievementBonusConfig> achievementBonusConfigs = achievementBonusConfigMapper.selectByMap(param);
        if(CollectionUtil.isNotEmpty(achievementBonusConfigs)){
            for (AchievementBonusConfig achievementBonusConfig : achievementBonusConfigs) {
                achievementBounsUpdate(byId,distributionOrder,levelFlag,achievementBonusConfig);
            }
        }

    }

    /**
     * 进行二级分销数量统计操作
     * @param order
     * @return
     */
    private void countTwoLevelNum(DistributionOrder order){
        Long userId = order.getUserId();
        //递归每级的处理方法
        countTwoLevelNumCommon(userId,order.getId(),2);
    }

    /**
     * 递归每级的处理方法
     */
    private void countTwoLevelNumCommon(long userId,long orderId,int level){
        User byId = userMapper.getById(userId);
        Long shareUserId = byId.getShareUserId();
        //保证一个单只能帮助 一个人一
        HashMap<String,Object> param = new HashMap<>();
        param.put("help_order_id",orderId);
        param.put("user_id",shareUserId);
        List<DistributionTwoLevelCountRecord> distributionTwoLevelCounts = distributionTwoLevelCountRecordMapper.selectByMap(param);
        if(!CollectionUtil.isEmpty(distributionTwoLevelCounts)){
            return;
        }
        boolean isNeedshare = shareUserId!=null;
        if(isNeedshare){
            //直接上级处理
            DistributionTwoLevelCount countTwo = new DistributionTwoLevelCount();
            countTwo.setUserId(shareUserId);
            countTwo = distributionTwoLevelCountMapper.selectOne(countTwo);
            if(countTwo == null){
                countTwo = new DistributionTwoLevelCount();
                countTwo.setUserId(shareUserId);
                countTwo.setNum(0);
                countTwo.setCreateTime(new Date());
                countTwo.setId(IdUtil.generateId());
                distributionTwoLevelCountMapper.insert(countTwo);
            }
            Integer num = countTwo.getNum();
            num = num == null?0:num;
            num++;
            countTwo.setNum(num);
            distributionTwoLevelCountMapper.updateById(countTwo);
            //进行两级分销订单汇总记录表的插入
            DistributionTwoLevelCountRecord record = new DistributionTwoLevelCountRecord();
            record.setHelpUserId(userId);
            record.setUserId(shareUserId);
            record.setId(IdUtil.generateId());
            record.setHelpOrderId(orderId);
            record.setTwoLevelCountId(countTwo.getId());
            distributionTwoLevelCountRecordMapper.insert(record);
            //助力上级
            jumpToQueue(countTwo);

            level--;
            if(level>0){
                countTwoLevelNumCommon(shareUserId,orderId,level);
            }
        }
    }

    @Override
    public void postProcess(Long orderId,Integer payType,Boolean isZero,boolean update) {
        isZero = isZero == null?false:isZero;
        //查询当前订单是否已经有位置
        DistributionOrderQueue query = new DistributionOrderQueue();
        query.setDistributionOrderId(orderId);
        DistributionOrderQueue distributionOrderQueue = distributionOrderQueueMapper.selectOne(query);
        DistributionOrder distributionOrder = distributionOrderMapper.selectById(orderId);
        distributionOrder.setOrderStatus(DistributionStatusDict.ORDER_STATUS_PAIED.getCn());
        Integer payTypeOld = distributionOrder.getPayType();
        if(payTypeOld==null || payTypeOld == 0){
            distributionOrder.setPayType(payType);
        }
        distributionOrderMapper.updateById(distributionOrder);
        //获取该分销商品
        Long distributionGoodsId = null;
        if(distributionOrderQueue==null){
            distributionGoodsId = distributionOrder.getDistributionGoodsId();
        }else{
            distributionGoodsId = distributionOrderQueue.getDistributionGoodsId();
        }
        DistributionGoods distributionGoods = distributionGoodsMapper.selectById(distributionGoodsId);
        String levelFlag = distributionGoods.getLevelFlag();
        //添加位置
        Boolean isMoneyPay = DistriButionPayTypeDict.checkCashPayType(payType);
        if(distributionOrderQueue==null){
            DistributionOrderQueue queueOrder = new DistributionOrderQueue();
            queueOrder.setBonusPresentation(BigDecimal.ZERO);
            queueOrder.setCreateTime(new Date());
            queueOrder.setDistributionGoodsId(distributionOrder.getDistributionGoodsId());
            queueOrder.setDistributionOrderId(orderId);
            queueOrder.setLevelFlag(levelFlag);
            queueOrder.setUserId(distributionOrder.getUserId());
            queueOrder.setSort(IdUtil.generateId());
            queueOrder.setRealSort(DistributionOrderQueue.getQueueSort(0,queueOrder.getBonusPresentation(),queueOrder.getSort()));
            distributionOrderQueueMapper.insert(queueOrder);
            distributionOrderQueue = queueOrder;
            //添加位置商品
            DistributionOrderQueueGoods queueGoods = new DistributionOrderQueueGoods();
            BeanUtil.copyProperties(distributionGoods,queueGoods);
            queueGoods.setOrderId(orderId);
            queueGoods.setCreateTime(new Date());
            queueGoods.setUpdateTime(new Date());
            //针对不同支付方式积分
            if(DistriButionPayTypeDict.checkFhType(payType)){
                //如果是分红支付,不赠送积分
                queueGoods.setBonusPoints(BigDecimal.ZERO);
            }
            distributionOrderQueueGoodsMapper.insert(queueGoods);
        }
        //添加分红记录
        DistributionBonusUserRecord record = new DistributionBonusUserRecord();
        record.setOrderId(orderId);
        record.setLevelFlag(levelFlag);
        record.setBonusPresentation(distributionGoods.getBonusPresentation());
        record.setCreateTime(new Date());
        record.setDes("购买"+distributionGoods.getDistributionName());
        record.setType(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_1.getCn());
        record.setBonusBalance( DecimalUtil.addArray(distributionGoods.getBonusPresentation(),distributionOrderQueue.getBonusPresentation()));
        distributionBonusUserRecordMapper.insert(record);
        //payType = distributionOrder.getPayType();
        Long userId = distributionOrder.getUserId();
        User byId = userMapper.getUserById(userId);
        //查看用户会员等级,如果现在购买的分销商等级大于当前等级,提升会员等级
        Integer level = byId.getLevel();
        level = level == null?0:level;
        log.info("postProcess userId:{},level:{}",userId,level);
        int levelGoods = UserLevelDict.getLevel(levelFlag);
        if(levelGoods>level){
            byId.setLevel(levelGoods);
            userMapper.update(byId);
        }
        //积分和推荐奖收益处理
        if(isMoneyPay
                //超高级复投
                || DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_4.getCn() == payType){
            TUserAccount acc = userAccountService.initUserAccountByUserId(userId);
            BigDecimal bonusPoints = distributionOrder.getBonusPoints();
            BigDecimal integral = acc.getIntegral();
            integral = DecimalUtil.addArray(bonusPoints,integral);
            acc.setIntegral(integral);
            tUserAccountMapper.updateById(acc);
            //添加积分流水记录
            IntegralTransaction it = new IntegralTransaction();
            it.setCreateTime(new Date());
            it.setType(IntegralTranTypeDict.INTEGRAL_TRAN_TYPE_DISTRUBUTION.getCn());
            it.setOrderId(orderId);
            it.setDes("购买分销商积分增加");
            it.setIntegral(distributionOrder.getBonusPoints());
            it.setUserId(distributionOrder.getUserId());
            it.setAccountTotalIntegral(integral);//变更后积分
            userAccountService.addIntegralTransaction(it);
            //查看是否给过分享奖励 如果没有,则将分享奖励给分享人
            Integer shareRewardsHave = byId.getShareRewardsHave();
            boolean isNeedshare = (byId.getShareUserId()!=null && (shareRewardsHave==null || shareRewardsHave!=1));
            /**
             * 推荐奖逻辑  现金购买或者超高级复投会产生推荐奖,
             * 如果有推荐人且第一次购买推荐奖,则推荐奖给推荐人
             * 其他推荐奖都给自身
             */
            if(isMoneyPay){
                //超高级复投取消推荐奖
                Long shareUserId =isNeedshare?byId.getShareUserId():byId.getId();
                BigDecimal shareRewards = null;
                Integer userLevel = 0;
                if(isNeedshare){
                    shareUserId =byId.getShareUserId();
                    userLevel = byId.getLevel();
                }else{
                    shareUserId =byId.getId();
                    User shareUser = userMapper.getById(shareUserId);
                    userLevel = shareUser.getLevel();
                }
                if(userLevel == null || userLevel<UserLevelDict.USER_LEVEL_2.getCn()){
                    shareRewards = distributionGoods.getVipShareRewards();
                }else{
                    shareRewards = distributionGoods.getShareRewards();
                }
                TUserAccount shareUseracc = userAccountService.initUserAccountByUserId(shareUserId);
                BigDecimal benefit = shareUseracc.getBenefit();
                benefit = DecimalUtil.addArray(benefit,shareRewards);
                shareUseracc.setBenefit(benefit);
                tUserAccountMapper.updateById(shareUseracc);
                //添加受益流水
                BenefitTransaction bt = new BenefitTransaction();
                bt.setCreateTime(new Date());
                bt.setType(isNeedshare?BenefitTranTypeDict.BENEFIT_TRAN_TYPE_200.getCn()
                        :BenefitTranTypeDict.BENEFIT_TRAN_TYPE_300.getCn());
                bt.setOrderId(orderId);
                bt.setCurrentTotalBenefit(benefit);
                bt.setDes(isMoneyPay?"购买":"财富复投"+distributionGoods.getDistributionName());
                bt.setBenefit(shareRewards);
                bt.setUserId(shareUserId);
                //获取此类型当前收益总额
                List<Integer> typeList = new ArrayList<>();
                typeList.add(bt.getType());
                BigDecimal sumType = benefitTransactionMapper.getSumByTypeList(shareUserId,typeList);
                bt.setCurrentTypeBenefit(DecimalUtil.addArray(bt.getBenefit(),sumType));
                benefitTransactionMapper.insert(bt);
                //如果被推荐人是第一次否购买分销商,则添加到分销关系链
                if(isNeedshare){
                    byId.setShareRewardsHave(1);
                    userMapper.update(byId);
                }
            }
        }

        if(isMoneyPay && !update){
            if(distributionOrder.getOrderType() != DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn()){
                BigDecimal distributionTotalPrice = byId.getDistributionTotalPrice();
                distributionTotalPrice = DecimalUtil.addArray(distributionTotalPrice,distributionOrder.getPrice());
                byId.setDistributionTotalPrice(distributionTotalPrice);
                userMapper.update(byId);
            }
            //统计分销商购买金额
            Message message=new Message();
            message.setUserId(-1L);
            message.setOrderId(orderId);
            message.setOrderType(2);
            message.setType(3);
            message.setMessage(byId.getUsername()+"购买了分销商订单,订单编号:"+distributionOrder.getOrderNo());
            userAccountService.addUserMessage(message);
            //维护首单标识
            String firstLevelFlag = byId.getFirstLevelFlag();
            if(StringUtils.isBlank(firstLevelFlag) || "0".equals(firstLevelFlag)){
                byId.setFirstLevelFlag(levelFlag);
                userMapper.update(byId);
            }
            //如果是金额支付,则统计二级分销数量
            countTwoLevelNum(distributionOrder);
            //进行业绩的累计 和  业绩提成的累积
            achievementCalculation( distributionOrder, distributionOrder.getPrice(), userId, levelFlag);
        }
        //如果不是零位将分红助益到首位之人
        if(!isZero){
            BigDecimal promotedPresentationLimit = distributionGoods.getPromotedPresentationLimit();
            DistributionOrderQueueVo order = distributionOrderQueueMapper.getFirstOrder(levelFlag,promotedPresentationLimit);
            record = new DistributionBonusUserRecord();
            record.setOrderId(orderId);
            record.setLevelFlag(levelFlag);
            record.setBonusPresentation(distributionGoods.getBonusPresentation());
            record.setCreateTime(new Date());
            record.setUseOrderId(order.getDistributionOrderId());
            record.setDes("互助其他订单");
            record.setType(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_3.getCn());
            record.setBonusBalance(BigDecimal.ZERO);
            distributionBonusUserRecordMapper.insert(record);
            BigDecimal bonusPresentation = order.getBonusPresentation();
            bonusPresentation = DecimalUtil.addArray(bonusPresentation,distributionGoods.getBonusPresentation());
            order.setBonusPresentation(bonusPresentation);
            record = new DistributionBonusUserRecord();
            record.setOrderId(order.getDistributionOrderId());
            record.setLevelFlag(levelFlag);
            record.setBonusPresentation(distributionGoods.getBonusPresentation());
            record.setCreateTime(new Date());
            record.setDes("被其他订单互助");
            record.setType(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_2.getCn());
            record.setBonusBalance(bonusPresentation);
            distributionBonusUserRecordMapper.insert(record);
            DistributionOrderQueue queueFirst = new DistributionOrderQueue();
            BeanUtil.copyProperties(order,queueFirst);
            Long queueFirstOrderId = queueFirst.getDistributionOrderId();
            DistributionOrder queueFirstOrder = distributionOrderMapper.selectById(queueFirstOrderId);
            queueFirst.setRealSort(DistributionOrderQueue.getQueueSort(queueFirstOrder.getVipOrders(),queueFirst.getBonusPresentation(),queueFirst.getSort()));
            distributionOrderQueueMapper.updateById(queueFirst);
            //保存助益记录
            DistributionHelpRelation helpRelation0 = new DistributionHelpRelation();
            helpRelation0.setUserId(distributionOrder.getUserId());
            helpRelation0.setHelpUserId(order.getUserId());
            helpRelation0.setHelpOrderId(order.getDistributionOrderId());
            helpRelation0.setLevelFlag(levelFlag);
            helpRelation0.setHelpMoney(distributionGoods.getBonusPresentation());
            helpRelation0.setType(0);
            helpRelation0.setCreateTime(new Date());
            helpRelation0.setDistributionOrderId(orderId);
            distributionHelpRelationMapper.insert(helpRelation0);

            DistributionHelpRelation helpRelation1 = new DistributionHelpRelation();
            helpRelation1.setUserId(distributionOrder.getUserId());
            helpRelation1.setHelpUserId(order.getUserId());
            helpRelation1.setLevelFlag(levelFlag);
            helpRelation1.setHelpOrderId(order.getDistributionOrderId());
            helpRelation1.setHelpMoney(distributionGoods.getBonusPresentation());
            helpRelation1.setType(1);
            helpRelation1.setCreateTime(new Date());
            helpRelation1.setDistributionOrderId(orderId);
            distributionHelpRelationMapper.insert(helpRelation1);
        }

    }

    @Override
    public MyBonusVo getMyBonusList(Integer packStatus, Long packageId) {
        MyBonusVo reselt = new MyBonusVo();
        Long currUid = SessionUtil.getCurrUid();
        User byId = userMapper.getById(currUid);
        reselt.setUserId(currUid);
        reselt.setLevel(byId.getLevel());
        DistributionOrderVo vo = new DistributionOrderVo();
        vo.setUserId(currUid);
        if(packStatus!=null){
            List<Integer> orderTypeList = new ArrayList<>();
            if(packStatus == 0){
                orderTypeList.add(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn());
                orderTypeList.add(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_0.getCn());
            }else{
                orderTypeList.add(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn());
            }
            vo.setOrderTypeList(orderTypeList);
        }
        if(packageId!=null){
            vo.setPId(packageId);
        }
        //去除分红购买的单子
        List<Integer> payTypeList = new ArrayList<>();
        vo.setPayTypeList(DistriButionPayTypeDict.getCashPayType());
        List<DistributionOrderVo> list = distributionOrderMapper.getDistributionOrderList(vo);
        List<DistributionOrderVo> sfList = new ArrayList<>();
        reselt.setSfList(sfList);
        List<DistributionOrderVo> ftChaoGaojiList = new ArrayList<>();
        reselt.setFtChaoGaojiList(ftChaoGaojiList);
        List<DistributionOrderVo> ftGaojiList = new ArrayList<>();
        reselt.setFtGaojiList(ftGaojiList);
        List<DistributionOrderVo> ftZhongjiList = new ArrayList<>();
        reselt.setFtZhongjiList(ftZhongjiList);
        List<DistributionOrderVo> ftChujiList = new ArrayList<>();
        reselt.setFtChujiList(ftChujiList);
        if(!CollectionUtils.isEmpty(list)){
            for (DistributionOrderVo distributionOrderVo : list) {
                Integer orderStatus = distributionOrderVo.getOrderStatus();
                if(orderStatus == null
                        || DistributionStatusDict.ORDER_STATUS_CREATED.getCn() == orderStatus
                        ||DistributionStatusDict.ORDER_STATUS_AUDIT.getCn() == orderStatus){
                    continue;
                }
                Integer orderType = distributionOrderVo.getOrderType();
                if(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn() == orderType){
                    Long distributionGoodsId = distributionOrderVo.getDistributionGoodsId();
                    DistributionGoodsPackage distributionGoodsPackage = distributionGoodsPackageMapper.selectById(distributionGoodsId);
                    distributionOrderVo.setDistributionName(distributionGoodsPackage.getPackageName());
                }
                Integer payType = distributionOrderVo.getPayType();
                String levelFlagInit = distributionOrderVo.getLevelFlagInit();
                if( DistriButionPayTypeDict.checkCashPayType(payType)){
                    sfList.add(distributionOrderVo);
                }else{
                    if(Constant.ZHONG_JI_DISTRIBUTION_FLAG.equals(levelFlagInit)){
                        distributionOrderVo.setDistributionName("中级分销商");
                        ftZhongjiList.add(distributionOrderVo);
                    }else if(Constant.GAO_JI_DISTRIBUTION_FLAG.equals(levelFlagInit)){
                        distributionOrderVo.setDistributionName("高级分销商");
                        ftGaojiList.add(distributionOrderVo);
                    }else if(Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG.equals(levelFlagInit)){
                        distributionOrderVo.setDistributionName("财富分销商");
                        ftChaoGaojiList.add(distributionOrderVo);
                    }
                }
                //进度处理
                String levelFlagQueue = distributionOrderVo.getLevelFlagQueue();
                distributionOrderVo.setProgress(getOrderProcess(levelFlagInit,levelFlagQueue,DistributionStatusDict.ORDER_STATUS_CLOSE.getCn() == orderStatus));
            }
        }
        return reselt;
    }

    /**
     * 获取分销订单进度
     * @return
     */
    private List<ProcessVo> getOrderProcess(String levelFlagInit,String levelFlagQueue,boolean isClose){
        String[]levelArray = {Constant.ZHONG_JI_DISTRIBUTION_FLAG,Constant.GAO_JI_DISTRIBUTION_FLAG,
                Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG};
        Integer start = null;
        Integer end = null;
        List<ProcessVo> result = new ArrayList<>();
        for (int i = 0; i < levelArray.length; i++) {
            String level = levelArray[i];
            if(start == null && level.equals(levelFlagInit)){
                start = i;
            }
            if(end == null && level.equals(levelFlagQueue)){
                end = i;
            }
            if(start!=null){
                DistributionGoods distributionGoods = new DistributionGoods();
                distributionGoods.setLevelFlag(level);
                distributionGoods = distributionGoodsMapper.selectOne(distributionGoods);
                ProcessVo vo = new ProcessVo();
                vo.setProcessName(distributionGoods.getDistributionName());
                int status = 0;
                if(end == null){
                    status = 2;
                }else{
                    if(level.equals(levelFlagQueue)){
                        status = 1;
                    }
                }
                vo.setProcessStatus(status);
                vo.setLevel(DistritubionLevelDict.getLevel(level));
                result.add(vo);
            }
        }
        if(isClose){
            ProcessVo processVo = result.get(result.size() - 1);
            processVo.setProcessStatus(2);
        }
        return result;
    }

    private  String getPhoneNum() {
        String[] Top3 = {"133", "149", "153", "173", "177",
                "180", "181", "189", "199", "130", "131", "132",
                "145", "155", "156", "166", "171", "175", "176", "185", "186", "166", "134", "135",
                "136", "137", "138", "139", "147", "150", "151", "152", "157", "158", "159", "172",
                "178", "182", "183", "184", "187", "188", "198", "170", "171"};
        //随机出真实号段   使用数组的length属性，获得数组长度，
        //通过Math.random（）*数组长度获得数组下标，从而随机出前三位的号段
        String firstNum = Top3[(int) (Math.random() * Top3.length)];
        //随机出剩下的8位数
        String lastNum = "";
        final int last = 8;
        for (int i = 0; i < last; i++) {
            //每次循环都从0~9挑选一个随机数
            lastNum += (int) (Math.random() * 10);
        }
        //最终将号段和尾数连接起来
        String phoneNum = firstNum+ lastNum;
        return phoneNum;
    }

    @Override
    public void inportOldData(MultipartFile file) {
        taskSwith = false;
        List<ImportUserVo> data = null;
        Map<String, User> userMap = new HashMap<>();
        Map<String, List<DistributionOrderVo>> orderMap = new HashMap<>();
        try{
            ExcelListener excelListener = new ExcelListener();
            data = EasyExcel.read(file.getInputStream(), ImportUserVo.class, excelListener).sheet("Sheet1").doReadSync();
        }catch (Exception e){
            log.info("inportOldData ",e);
        }
        if(!CollectionUtils.isEmpty(data)){
            Map<String,String> phoneMap = new HashMap<>();
            //初始化用户
            Random rr = new Random();
            for (ImportUserVo datum : data) {
                String name = datum.getField1();
                User user = userMap.get(name);
                if(user == null){
                    user = new User();
                    long id = IdUtil.generateId();
                    user.setId(id);
                    user.setUsername(name);
                    user.setName(name);
                    String field6 = datum.getField6();
                    if(StringUtils.isBlank(field6)){
                        field6 = phoneMap.get(name);
                        if(StringUtils.isBlank(field6)){
                            field6 = getPhoneNum();
                        }
                    }
                    phoneMap.put("name",field6);
                    user.setUserPhone(field6);
                    user.setWxPhone(field6);
                    user.setLevel(1);
                    user.setPassword("111111");
                    user.setType(1);
                    user.setStop(0);
                    user.setShareRewardsHave(0);
                    user.setShareGoodsRewardsHave(0);
                    user.setDistributionTotalPrice(BigDecimal.ZERO);
                    userService.addUser(user);
                    userMap.put(name,user);
                    //授权为客户角色
                    List<Long> roleIds = new ArrayList<>();
                    roleIds.add(Constant.CLIENT_ROLE_ID);
                    user.setRoleIds(roleIds);
                    userService.grant(user);
                    //初始化账户表
                    TUserAccount acc = new TUserAccount();
                    acc.setUserId(user.getId());
                    acc.setBenefit(BigDecimal.ZERO);
                    acc.setIntegral(BigDecimal.ZERO);
                    acc.setCreateTime(new Date());
                    userAccountService.save(acc);
                }
            }
            for (ImportUserVo datum : data) {
                String field3 = datum.getField3();
                //维护推荐人
                String name = datum.getField1();
                User user = userMap.get(name);
                Long shareUserId = user.getShareUserId();
                String name2 = datum.getField2();
                if(shareUserId == null && StringUtils.isNotBlank(name2)){
                    User user1 = userMap.get(name2);
                    log.info("setShareUserId name:{}",name);
                    user.setShareUserId(user1.getId());
                    userMapper.update(user);
                    DistributionShareRelation relation = new DistributionShareRelation();
                    relation.setCreateTime(new Date());
                    relation.setUserId(user.getId());
                    relation.setShareUserId(user.getShareUserId());
                    relation.setOrderId(null);
                    insertRelation(relation);
                }
                //保存订单
                Long distributionGoodsId =  null;
                boolean isVip = false;
                if("财富".equals(field3)){
                    distributionGoodsId = 4L;
                }else if("高级".equals(field3)){
                    distributionGoodsId = 3L;
                }else if("中级".equals(field3)){
                    distributionGoodsId = 2L;
                }else if("VIP".equals(field3)){
                    isVip = true;
                }
                if(distributionGoodsId!=null){
                    DistributionOrderVo vo = new DistributionOrderVo();
                    vo.setDistributionGoodsId(distributionGoodsId);
                    vo.setPayType(DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn());
                    vo.setUserId(user.getId());
                    vo.setOrderType(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_0.getCn());
                    DistributionOrderVo distributionOrderVo = addDistributionOrder(vo,false);
                    postProcess(distributionOrderVo.getId(),DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn(),false,false);
                }else if(isVip){
                    //如果是vip 给购买人添加288积分 并给推荐人144的收益
                    TUserAccount tUserAccount = userAccountService.initUserAccountByUserId(user.getId());
                    BigDecimal integral = tUserAccount.getIntegral();
                    integral = DecimalUtil.addArray(integral, new BigDecimal("288"));
                    tUserAccount.setIntegral(integral);
                    tUserAccountMapper.updateById(tUserAccount);
                    TUserAccount shareUserAccount = userAccountService.initUserAccountByUserId(user.getShareUserId());
                    if(shareUserAccount!=null){
                        BigDecimal benefit = shareUserAccount.getBenefit();
                        benefit = DecimalUtil.addArray(benefit, new BigDecimal("144"));
                        shareUserAccount.setBenefit(benefit);
                        tUserAccountMapper.updateById(shareUserAccount);
                    }
                }
            }
        }
        taskSwith = true;
    }

    @Override
    public void reviewOfflineOrder(DistributionOrderVo vo) {
        Long ordersId = vo.getId();
        Assert.notNull(ordersId,"参数错误,请传输订单号");
        DistributionOrder orders = distributionOrderMapper.selectById(ordersId);
        Assert.notNull(orders,"参数错误,此订单");
        Integer orderStatus = orders.getOrderStatus();
        Assert.isTrue(orders!=null && orderStatus < DistributionStatusDict.ORDER_STATUS_PAIED.getCn(),"参数错误,已经是付款状态");
        Integer payType = orders.getPayType();
        String ordersNo = orders.getOrderNo();
        Integer orderType = orders.getOrderType();
        //线下支付才需要审核
        boolean isOffline = payType!=null &&
                (payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_5.getCn() ||
                payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_6.getCn()) ;
        Assert.isTrue(isOffline,"线上支付,无需审核");
        //获取支付金额
        BigDecimal price = orders.getPrice();
        long checkoutId = IdUtil.generateId();
        Payment payment = new Payment();
        payment.setPayNo(OrderCodeUtil.getPayCode(orders.getUserId()));
        payment.setStartTime(new Date());
        payment.setPaymentResult("线下支付");
        payment.setPaymentStatus(PaymentStatusDict.PAYMENT_STATUS_SUCCESS.getCn());
        payment.setUserId(orders.getUserId());
        payment.setPayType(PaymentTypeDict.PAYMENT_TYPE_PAY.getCn());
        payment.setOrderId(ordersNo);
        payment.setCheckoutId(IdUtil.generateId());
        payment.setAmount(price.multiply(new BigDecimal("100")));
        payment.setOrderType(OrderTypeDict.ORDER_TYPE_DISTRBUTION.getCn());
        payment.setOfflineStatus(OrderLineStatusDict.ORDER_LINE_STATUS_OFF.getCn());
        payment.setId(IdUtil.generateId());
        payment.setCreateTime(new Date());
        payment.setCompleteTime(new Date());
        payment.setPaymentResult("线下支付成功");
        paymentMapper.insert(payment);
        orders.setCheckoutId(checkoutId);
        orders.setReceiptUrl(vo.getReceiptUrl());
        distributionOrderMapper.updateById(orders);

        if(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn() == orderType){
            packAgePostProcess(ordersId,DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_5.getCn(),false,false);
        }else{
            postProcess(ordersId,DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_5.getCn(),false,false);
        }

    }

    @Override
    public DistributionOrderVo submitPayEvidence(DistributionOrderVo vo) {
        Long id = vo.getId();
        Assert.notNull(id,"参数错误,订单ID不可为空");
        DistributionOrder distributionOrder = distributionOrderMapper.selectById(id);
        Assert.notNull(distributionOrder,"参数错误,无当前订单");
        Integer orderStatus = distributionOrder.getOrderStatus();
        Assert.isTrue(DistributionStatusDict.ORDER_STATUS_CREATED.getCn() == orderStatus,"参数错误,当前订单非代付款状态");
        distributionOrder.setOrderStatus(DistributionStatusDict.ORDER_STATUS_AUDIT.getCn());
        Integer payType = distributionOrder.getPayType();
        if(payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_6.getCn()){
            distributionOrder.setReceiptUrl(vo.getReceiptUrl());
            distributionOrder.setBankCardNum(vo.getBankCardNum());
            distributionOrder.setBankId(vo.getBankId());
        }
        distributionOrderMapper.updateById(distributionOrder);
        BeanUtil.copyProperties(distributionOrder,vo);
        return vo;
    }

    @Override
    public DataTable<DistributionOrderVo> getReadyPayOrderList() {
        Long currUid = SessionUtil.getCurrUid();
        DistributionOrderVo vo = new DistributionOrderVo();
        vo.setStart(0);
        vo.setLength(10000000);
        vo.setUserId(currUid);
        List<Integer> orderStatusList = new ArrayList<>();
        orderStatusList.add(DistributionStatusDict.ORDER_STATUS_CREATED.getCn());
        orderStatusList.add(DistributionStatusDict.ORDER_STATUS_AUDIT.getCn());
        vo.setOrderStatusList(orderStatusList);
        List<Integer> payTypeList = new ArrayList<>();
        payTypeList.add(DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_5.getCn());
        payTypeList.add(DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_6.getCn());
        vo.setPayTypeList(payTypeList);
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn());
        orderTypeList.add(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_0.getCn());
        vo.setOrderTypeList(orderTypeList);
        return getDistributionOrderList(vo);
    }

    @Override
    public DistributionOrderVo getDistributionOrderDetail(long orderId,Integer level) {
        DistributionOrder distributionOrder = distributionOrderMapper.selectById(orderId);
        Assert.notNull(distributionOrder,"参数错误,无此订单");
        Long userId = distributionOrder.getUserId();
        DistributionOrderVo vo = new DistributionOrderVo();
        vo.setId(orderId);
        vo.setStart(0);
        vo.setLength(10000000);
        DataTable<DistributionOrderVo> data = getDistributionOrderList(vo);
        List<DistributionOrderVo> orderList = data.getData();
        DistributionOrderVo distributionOrderVo = orderList.get(0);
        String levelFlagQueue = distributionOrderVo.getLevelFlagQueue();
        Integer currlevel = DistritubionLevelDict.getLevel(levelFlagQueue);
        if(level == null){
            level = currlevel;
        }
        //小程序详情页面
        String levelFlag = DistritubionLevelDict.getDescByCn(level);
        Map<String,Object> param = new HashMap<>();
        param.put("order_id",orderId);
        List<DistributionOrderQueueGoods> distributionOrderQueueGoodsList = distributionOrderQueueGoodsMapper.selectByMap(param);
        BigDecimal bonusPoints = null;
        BigDecimal bonusPresentation = null;
        if(!CollectionUtil.isEmpty(distributionOrderQueueGoodsList) && level == currlevel){
            DistributionOrderQueue query = new DistributionOrderQueue();
            query.setDistributionOrderId(orderId);
            query = distributionOrderQueueMapper.selectOne(query);
            bonusPresentation = query.getBonusPresentation();
        }
        DistributionOrderQueueGoods query = new DistributionOrderQueueGoods();
        query.setOrderId(orderId);
        query.setLevelFlag(levelFlag);
        DistributionOrderQueueGoods distributionOrderQueueGoods = distributionOrderQueueGoodsMapper.selectOne(query);
        if(distributionOrderQueueGoods != null){
            bonusPoints = distributionOrderQueueGoods.getBonusPoints();
        }
        distributionOrderVo.setCurrentLevelBonusPoints(bonusPoints == null?BigDecimal.ZERO:bonusPoints);
        //获取互助我的 0:我被助益 1:我助益别人
        distributionOrderVo.setHelpMeList(getOrderHelpList(userId,0,orderId,levelFlag));
        //获取我互助的 0:我被助益 1:我助益别人
        distributionOrderVo.setMeHelpList(getOrderHelpList(userId,1,orderId,levelFlag));
        //查询子集订单 查询收益记录
        param = new HashMap<>();
        param.put("order_id",orderId);
        param.put("level_flag",levelFlag);
        List<DistributionBonusUserRecord> subOrderList = distributionBonusUserRecordMapper.selectByMap(param);
        List<DistributionbonusUserRecordVo> subOrderVoList = new ArrayList<>();
        if(!CollectionUtil.isEmpty(subOrderList)){
            for (DistributionBonusUserRecord distributionBonusUserRecord : subOrderList) {
                Integer type = distributionBonusUserRecord.getType();
                if(DistributionBonusRecordTypeDict.checkUseType(type)){
                    DistributionbonusUserRecordVo recordVo = new DistributionbonusUserRecordVo();
                    if(level != currlevel){
                        bonusPresentation = DecimalUtil.addArray(bonusPresentation,distributionBonusUserRecord.getBonusPresentation());
                    }
                    recordVo.setBonusMoney(distributionBonusUserRecord.getBonusPresentation());
                    recordVo.setTime(distributionBonusUserRecord.getCreateTime());
                    recordVo.setType(type);
                    recordVo.setTypeName(distributionBonusUserRecord.getDes());
                    subOrderVoList.add(recordVo);
                    if(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_4.getCn()== type){
                        Long userOrderId = distributionBonusUserRecord.getUseOrderId();
                        DistributionOrder distributionOrderUse = distributionOrderMapper.selectById(userOrderId);
                        recordVo.setOrderNo(distributionOrderUse.getOrderNo());
                        recordVo.setOrderId(distributionOrderUse.getId());
                    }else if(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_5.getCn()== type){
                        recordVo.setOrderNo(distributionOrder.getOrderNo());
                        recordVo.setOrderId(distributionOrder.getId());
                    }
                }
            }
        }
        distributionOrderVo.setCurrentLevelBonusPresentation(bonusPresentation);
        distributionOrderVo.setBonusUserRecordList(subOrderVoList);
        distributionOrderVo.setLevelQuery(level);
        return distributionOrderVo;
    }

    /**
     * 获取互助订单
     * @param currUid 用户ID
     * @param type 0:我被助益 1:我助益别人
     * @param orderId
     * @param levelFlag
     * @return
     */
    private  List<DistributionHelpRelationVo> getOrderHelpList(Long currUid,Integer type,Long orderId,String levelFlag){
        //获取互助我的 0:我被助益 1:我助益别人
        List<DistributionHelpRelationVo> helpList = distributionHelpRelationMapper.getHelpRelation(currUid,type,orderId,levelFlag);
        if(CollectionUtil.isNotEmpty(helpList)){
            for (DistributionHelpRelationVo distributionHelpRelationVo : helpList) {
                Long helpId = null;
                if(type == 0){
                    helpId = distributionHelpRelationVo.getDistributionOrderId();
                    DistributionOrder distributionOrder = distributionOrderMapper.selectById(helpId);
                    distributionHelpRelationVo.setDistributionOrderNo(distributionOrder.getOrderNo());
                }else{
                    helpId = distributionHelpRelationVo.getHelpOrderId();
                    DistributionOrder distributionOrder = distributionOrderMapper.selectById(helpId);
                    distributionHelpRelationVo.setHelpOrderNo(distributionOrder.getOrderNo());
                }

            }
        }
       return helpList;
    }

    @Override
    public RestListRespResult<DistributionOrderDetailPcVo> getOrderDetailForPc(long orderId) {
        RestListRespResult<DistributionOrderDetailPcVo> result = new RestListRespResult<>();
        List<DistributionOrderDetailPcVo> data = new ArrayList<>();
        result.setData(data);
        DistributionOrder distributionOrder = distributionOrderMapper.selectById(orderId);
        Assert.notNull(distributionOrder,"参数错误,无此订单");
        Map<String,Object> param = new HashMap<>();
        param.put("order_id",orderId);

        List<DistributionOrderQueueGoods> distributionOrderQueueGoodsList = distributionOrderQueueGoodsMapper.selectByMap(param);
        Integer payType = distributionOrder.getPayType();
        if(!CollectionUtils.isEmpty(distributionOrderQueueGoodsList)){
            DistributionOrderQueue query = new DistributionOrderQueue();
            query.setDistributionOrderId(orderId);
            query = distributionOrderQueueMapper.selectOne(query);
            String levelFlagQueue = query.getLevelFlag();
            BigDecimal helpBonusPresentation = BigDecimal.ZERO;
            for (int i = 0; i < distributionOrderQueueGoodsList.size(); i++) {
                DistributionOrderQueueGoods distributionOrderQueueGoods = distributionOrderQueueGoodsList.get(i);
                DistributionOrderDetailPcVo vo = new DistributionOrderDetailPcVo();
                vo.setId(orderId);
                vo.setOrderNo(distributionOrder.getOrderNo());
                vo.setDistributionName(distributionOrderQueueGoods.getDistributionName());
                if(i == 0){
                    vo.setPayTypeName(DistriButionPayTypeDict.getDescByCn(payType));
                    if(DistriButionPayTypeDict.checkFhType(payType)){
                        vo.setPayMoney(distributionOrderQueueGoods.getPromotedPresentationAdd());
                    }else{
                        vo.setPayMoney(distributionOrderQueueGoods.getPrice());
                    }
                }else{
                    vo.setPayTypeName("使用互助金升级");
                    vo.setPayMoney(distributionOrderQueueGoods.getPromotedPresentationAdd());
                }
                vo.setBonusPoints(distributionOrderQueueGoods.getBonusPoints());
                vo.setBonusPresentation(distributionOrderQueueGoods.getBonusPresentation());
                //获取互助情况
                String levelFlag = distributionOrderQueueGoods.getLevelFlag();
                if(levelFlagQueue.equals(levelFlag)){
                    helpBonusPresentation = query.getBonusPresentation();
                }
                vo.setHelpMeList(getOrderHelpList(distributionOrder.getUserId(),0,orderId,levelFlag));
                vo.setMeHelpList(getOrderHelpList(distributionOrder.getUserId(),1,orderId,levelFlag));
                //收益使用情况
                param = new HashMap<>();
                param.put("order_id",orderId);
                param.put("level_flag",levelFlag);
                List<DistributionBonusUserRecord> subOrderList = distributionBonusUserRecordMapper.selectByMap(param);
                if(!CollectionUtil.isEmpty(subOrderList)){
                    for (DistributionBonusUserRecord distributionBonusUserRecord : subOrderList) {
                        Integer type = distributionBonusUserRecord.getType();
                        BigDecimal bonusPresentation = distributionBonusUserRecord.getBonusPresentation();
                        if(DistributionBonusRecordTypeDict.checkUseType(type)){
                            helpBonusPresentation = helpBonusPresentation = DecimalUtil.addArray(bonusPresentation,helpBonusPresentation);
                        }
                        if(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_4.getCn()== type){
                            Long userOrderId = distributionBonusUserRecord.getUseOrderId();
                            DistributionOrder distributionOrderUse = distributionOrderMapper.selectById(userOrderId);
                            DistributionOrderGoods distributionOrderGoods=new DistributionOrderGoods();
                            distributionOrderGoods.setOrderId(userOrderId);
                            //distributionOrderGoods.setLevelFlag(distributionOrderQueueGoods.getLevelFlag());
                            distributionOrderGoods=distributionOrderGoodsMapper.selectOne(distributionOrderGoods);
                            String levelFlag1 = distributionOrderGoods.getLevelFlag();
                            if(Constant.ZHONG_JI_DISTRIBUTION_FLAG.equals(levelFlag1)){
                                vo.setZhongJiMoney(bonusPresentation);
                                vo.setZhongJiOrderNo(distributionOrderUse.getOrderNo());
                            }else{
                                vo.setGaoJiMoney(bonusPresentation);
                                vo.setGaoJiOrderNo(distributionOrderUse.getOrderNo());
                            }
                        }else if(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_5.getCn()== type){
                            vo.setUpgradeMoney(bonusPresentation);
                        }else if(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_6.getCn()== type){
                            vo.setBenefitMoney(bonusPresentation);
                        }
                    }
                }
                vo.setHelpBonusPresentation(helpBonusPresentation);
                data.add(vo);
            }
        }
        return result;
    }

    @Override
    public DataTable<DistributionShareRelationPcVo> getShareRelationForPc(DistributionShareRelationPcVo vo) {
        PageHelper.startPage(vo.getStart(), vo.getLength());
        List<DistributionShareRelationPcVo> list = distributionShareRelationMapper.getShareRelationForPc(vo);
        if(!CollectionUtils.isEmpty(list)){
            for (DistributionShareRelationPcVo distributionShareRelationPcVo : list) {
                Long userId = distributionShareRelationPcVo.getUserId();
                //分销订单数量
                Integer orderNum = distributionOrderMapper.getOrderNumByUserId(userId, null);
                distributionShareRelationPcVo.setDistributionOrderNum(orderNum);
                //最新购买时间
                DistributionOrderVo distributionOrder = distributionOrderMapper.getNewOrder(userId);
                if(distributionOrder!=null){
                    distributionShareRelationPcVo.setCreateTime(distributionOrder.getCreateTime());
                }
                DistributionOrderVo orderVo = new DistributionOrderVo();
                orderVo.setUserId(userId);
                List<DistributionOrderVo> distributionOrderList = distributionOrderMapper.getDistributionOrderList(orderVo);
                distributionShareRelationPcVo.setOrderList(distributionOrderList);
            }
        }
        DataTable<DistributionShareRelationPcVo> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) list).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(vo.getDraw());
        tables.setData(list);
        return tables;
    }

    @Override
    public int insertRelation(DistributionShareRelation relation) {
        return distributionShareRelationMapper.insert(relation);
    }

    @Override
    public void saveOrUpdatePackage(DistributionGoodsPackageVo vo) {
        String packageName = vo.getPackageName();
        Map<String,Object> params = new HashMap<>();
        Long id = vo.getId();
        boolean isSave = id == null;
        String pre = isSave?"添加失败,":"更新失败,";
        //查询是否有同名的分销商
        params.put("package_name",packageName);
        params.put("status",1);
        params.put("deleted",0);
        List<DistributionGoodsPackage> packageList = distributionGoodsPackageMapper.selectByMap(params);
        if(isSave){
            Assert.isTrue(CollectionUtils.isEmpty(packageList),pre+"已有同名套餐包");
        }else{
            if(!CollectionUtil.isEmpty(packageList)){
                for (DistributionGoodsPackage distributionGoodsPackage : packageList) {
                    Long nameId = distributionGoodsPackage.getId();
                    Assert.isTrue(nameId.equals(id),pre+"已有同名套餐包");
                }
            }
        }
        List<DistributionPackageGoodsVo> distributionGoodList = vo.getDistributionGoodList();
        Assert.isTrue(!CollectionUtils.isEmpty(distributionGoodList),pre+"套餐内必须有分销商品");
        Map<Long,DistributionPackageGoods> oldSkuMap = new HashMap<>();
        if(isSave){
            Long packageId  = IdUtil.generateId();
            vo.setId(packageId);
            DistributionGoodsPackage goodPackage = new DistributionGoodsPackage();
            BeanUtil.copyProperties(vo,goodPackage, CopyOptions.create().setIgnoreNullValue(true));
            distributionGoodsPackageMapper.insert(goodPackage);
        }else{
            DistributionGoodsPackage distributionGoodsPackage = distributionGoodsPackageMapper.selectById(id);
            BeanUtil.copyProperties(vo,distributionGoodsPackage, CopyOptions.create().setIgnoreNullValue(true));
            distributionGoodsPackageMapper.updateById(distributionGoodsPackage);
            params.clear();
            params.put("package_id",id);
            params.put("deleted",0);
            List<DistributionPackageGoods> goodsList = distributionPackageGoodsMapper.selectByMap(params);
            if(CollectionUtil.isNotEmpty(goodsList)){
                if(!CollectionUtil.isEmpty(goodsList)){
                    for (DistributionPackageGoods distributionPackageGoods : goodsList) {
                        oldSkuMap.put(distributionPackageGoods.getId(),distributionPackageGoods);
                    }
                }
            }
        }
        if(CollectionUtil.isNotEmpty(distributionGoodList)){
            for (DistributionPackageGoodsVo distributionPackageGoodsVo : distributionGoodList) {
                Long packageGoodsId = distributionPackageGoodsVo.getId();
                if(packageGoodsId == null || packageGoodsId == 0){
                    DistributionPackageGoods good = new DistributionPackageGoods();
                    BeanUtil.copyProperties(distributionPackageGoodsVo,good, CopyOptions.create().setIgnoreNullValue(true));
                    packageGoodsId  = IdUtil.generateId();
                    good.setId(packageGoodsId);
                    good.setPackageId(vo.getId());
                    distributionPackageGoodsMapper.insert(good);
                }else{
                    DistributionPackageGoods distributionPackageGoods = oldSkuMap.get(distributionPackageGoodsVo.getId());
                    if(distributionPackageGoods != null){
                        oldSkuMap.remove(distributionPackageGoodsVo.getId());
                        BeanUtil.copyProperties(distributionPackageGoodsVo,distributionPackageGoods, CopyOptions.create().setIgnoreNullValue(true));
                        distributionPackageGoodsMapper.updateById(distributionPackageGoods);
                    }
                }
            }
        }
        if(CollectionUtil.isNotEmpty(oldSkuMap)){
            for (Long aLong : oldSkuMap.keySet()) {
                distributionPackageGoodsMapper.deleteById(aLong);
            }
        }
    }

    @Override
    public DistributionOrderVo addDistributionPackageOrder(DistributionOrderVo vo, boolean isAuth) {
        User byId = checkAuth(vo.getUserId(), isAuth);
        long currUid = byId.getId();
        Long packageId = vo.getPackageId();
        if(packageId == null){
            packageId = vo.getDistributionGoodsId();
        }
        Assert.notNull(packageId,"参数错误,请传输分销套餐ID");
        DistributionGoodsPackage distributionGoodsPackage = distributionGoodsPackageMapper.selectById(packageId);
        Assert.notNull(distributionGoodsPackage,"参数错误,无此分销套餐商品");
        Map<String,Object> params = new HashMap<>();
        params.put("package_id",distributionGoodsPackage.getId());
        params.put("deleted",0);
        List<DistributionPackageGoods> packageGoodList = distributionPackageGoodsMapper.selectByMap(params);
        Assert.isTrue(CollectionUtil.isNotEmpty(packageGoodList),"此套餐商品未配置分销商品");
        //获取当前人用户信息
        vo.setUserId(currUid);
        vo.setShareUserId(byId.getShareUserId());
        vo.setDistributionGoodsId(distributionGoodsPackage.getId());
        vo.setOrderNo(OrderCodeUtil.getDistributionPackCode(currUid));
        vo.setOrderStatus(DistributionStatusDict.ORDER_STATUS_CREATED.getCn());
        vo.setOrderType(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_1.getCn());
        Integer payType = vo.getPayType();
        TUserAccount tUserAccount = null;
        BigDecimal benefitNew = null;
        if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_6.getCn()){
            //如果是线下支付需要传输转账号码
            PlatformBankCard platformBankCard = new PlatformBankCard();
            platformBankCard.setStop(0);
            platformBankCard = platformBankCardMapper.selectOne(platformBankCard);
            Assert.notNull(platformBankCard,"没有配置平台转账号码");
            vo.setPlatformId(platformBankCard.getId());
            vo.setPlatformBankId(platformBankCard.getBankId());
            vo.setBankNum(platformBankCard.getBankNum());
            vo.setBankName(platformBankCard.getBankName());
            vo.setBankUserName(platformBankCard.getBankUserName());
        }else if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn()){
            //如果是收益金支付,则判断收益是否足以支付
            tUserAccount = userAccountService.initUserAccountByUserId(currUid);
            BigDecimal benefit = tUserAccount.getBenefit();
            benefitNew = DecimalUtil.subArrayOriginalValue(benefit, distributionGoodsPackage.getPrice());
            tUserAccount.setBenefit(benefitNew);
            Assert.isTrue(benefitNew.compareTo(BigDecimal.ZERO)>=0,"收益金额不足,请选择其他支付方式");
            vo.setOrderStatus(DistributionStatusDict.ORDER_STATUS_PAIED.getCn());
        }
        //添加子订单
        BigDecimal bonusPresentation = BigDecimal.ZERO;
        BigDecimal originalPrice = BigDecimal.ZERO;
        BigDecimal price = distributionGoodsPackage.getPrice();
        for (DistributionPackageGoods distributionPackageGoods : packageGoodList) {
            Integer goodNum = distributionPackageGoods.getGoodNum();
            goodNum = goodNum == null?0:goodNum;
            Long goodId = distributionPackageGoods.getGoodId();
            DistributionGoods distributionGoods = distributionGoodsMapper.selectById(goodId);
            Assert.notNull(distributionGoods,"套餐内分销商品已下架");
            originalPrice = DecimalUtil.addArray(originalPrice,DecimalUtil.mulArray(distributionGoods.getPrice(),new BigDecimal(goodNum+"")));
            for (int i = 0; i < goodNum; i++) {
                bonusPresentation = DecimalUtil.addArray(distributionGoods.getBonusPresentation(),bonusPresentation);
            }
        }
        log.info("addDistributionPackageOrder originalPrice:{}",originalPrice);
        vo.setPrice(distributionGoodsPackage.getPrice());
        vo.setBonusPresentation(bonusPresentation);
        DistributionOrder order = new DistributionOrder();
        BeanUtil.copyProperties(vo,order);
        order.setCreateTime(new Date());
        distributionOrderMapper.insert(order);
        long packageOrderId = order.getId();
        BigDecimal discount = DecimalUtil.getRate(originalPrice,price);
        for (DistributionPackageGoods distributionPackageGoods : packageGoodList) {
            Long goodId = distributionPackageGoods.getGoodId();
            DistributionGoods distributionGoods = distributionGoodsMapper.selectById(goodId);
            Assert.notNull(distributionGoods,"套餐内分销商品已下架");
            Integer goodNum = distributionPackageGoods.getGoodNum();
            DistributionOrderVo distributionOrder = new DistributionOrderVo();
            distributionOrder.setDistributionGoodsId(goodId);
            distributionOrder.setPayType(vo.getPayType());
            distributionOrder.setUserId(currUid);
            distributionOrder.setPackageId(packageId);
            distributionOrder.setPId(packageOrderId);
            distributionOrder.setPrice(DecimalUtil.getRate(distributionGoods.getPrice(),discount));
            distributionOrder.setOrderType(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_2.getCn());
            for (int i = 0; i < goodNum; i++) {
                addDistributionOrder(distributionOrder,false);
            }
            DistributionPackageOrderGoods orderGoods = new DistributionPackageOrderGoods();
            BeanUtil.copyProperties(distributionPackageGoods,orderGoods);
            orderGoods.setOrderId(packageOrderId);
            distributionPackageOrderGoodsMapper.insert(orderGoods);
        }
        //收益支付,子订单的处理
        if(payType!=null && payType == DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn()){
            tUserAccountMapper.updateById(tUserAccount);
            BenefitTransaction bt = new BenefitTransaction( currUid,currUid,packageOrderId,benefitNew,
                    BenefitTranTypeDict.BENEFIT_TRAN_TYPE_1100.getCn(),  distributionGoodsPackage.getPrice().negate(), "购买分销商套餐包");
            userAccountService.addBenefitTransaction(bt);
            packAgePostProcess(order.getId(), DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_8.getCn(),false,false);
        }
        vo.setId(order.getId());
        return vo;
    }

    @Override
    public void saveOrUpdateAchievementConfig(AchievementBonusConfigVo vo) {
        String configName = vo.getConfigName();
        Map<String,Object> params = new HashMap<>();
        Long id = vo.getId();
        boolean isSave = id == null;
        String pre = isSave?"添加失败,":"更新失败,";
        //查询是否有同名的分销商
        params.put("config_name",configName);
        params.put("status",0);
        params.put("deleted",0);
        List<AchievementBonusConfig> achievementConfigList = achievementBonusConfigMapper.selectByMap(params);
        if(isSave){
            Assert.isTrue(CollectionUtils.isEmpty(achievementConfigList),pre+"已有同名业绩奖配置");
        }else{
            if(!CollectionUtil.isEmpty(achievementConfigList)){
                for (AchievementBonusConfig achievementBonusConfig : achievementConfigList) {
                    Long nameId = achievementBonusConfig.getId();
                    Assert.isTrue(nameId.equals(id),pre+"已有同名业绩奖配置");
                }
            }
        }
        params.clear();
        params.put("level_flag",vo.getLevelFlag());
        params.put("status",0);
        params.put("deleted",0);
        achievementConfigList = achievementBonusConfigMapper.selectByMap(params);
        if(isSave){
            Assert.isTrue(CollectionUtils.isEmpty(achievementConfigList),pre+"已经有同级级别业绩奖配置");
        }else{
            if(!CollectionUtil.isEmpty(achievementConfigList)){
                for (AchievementBonusConfig achievementBonusConfig : achievementConfigList) {
                    Long nameId = achievementBonusConfig.getId();
                    Assert.isTrue(nameId.equals(id),pre+"已经有同级级别业绩奖配置");
                }
            }
        }
        List<AchievementBonusConfigDetailVo> configDetailList = vo.getConfigDetailList();
        Assert.isTrue(!CollectionUtils.isEmpty(configDetailList),pre+"套餐内必须有分销商品");
        Map<Long,AchievementBonusConfigDetail> oldSkuMap = new HashMap<>();
        if(isSave){
            Long configId  = IdUtil.generateId();
            vo.setId(configId);
            AchievementBonusConfig achievementConfig = new AchievementBonusConfig();
            BeanUtil.copyProperties(vo,achievementConfig, CopyOptions.create().setIgnoreNullValue(true));
            achievementBonusConfigMapper.insert(achievementConfig);
        }else {
            AchievementBonusConfig achievementBonusConfigOld = achievementBonusConfigMapper.selectById(id);
            BeanUtil.copyProperties(vo, achievementBonusConfigOld, CopyOptions.create().setIgnoreNullValue(true));
            achievementBonusConfigMapper.updateById(achievementBonusConfigOld);
            params.clear();
            params.put("config_id", id);
            params.put("deleted",0);
            List<AchievementBonusConfigDetail> achievementBonusConfigDetailList = achievementBonusConfigDetailMapper.selectByMap(params);
            if (!CollectionUtil.isEmpty(achievementBonusConfigDetailList)) {
                for (AchievementBonusConfigDetail achievementBonusConfigDetail : achievementBonusConfigDetailList) {
                    oldSkuMap.put(achievementBonusConfigDetail.getId(), achievementBonusConfigDetail);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(configDetailList)) {
            for (AchievementBonusConfigDetailVo achievementBonusConfigDetailVo : configDetailList) {
                Long configDetailId = achievementBonusConfigDetailVo.getId();
                if (configDetailId == null || configDetailId == 0) {
                    AchievementBonusConfigDetail achievementBonusConfigDetail = new AchievementBonusConfigDetail();
                    BeanUtil.copyProperties(achievementBonusConfigDetailVo, achievementBonusConfigDetail, CopyOptions.create().setIgnoreNullValue(true));
                    Long configDetailIdNew = IdUtil.generateId();
                    achievementBonusConfigDetail.setId(configDetailIdNew);
                    achievementBonusConfigDetail.setConfigId(vo.getId());
                    achievementBonusConfigDetailMapper.insert(achievementBonusConfigDetail);
                } else {
                    AchievementBonusConfigDetail achievementBonusConfigDetail = oldSkuMap.get(achievementBonusConfigDetailVo.getId());
                    if (achievementBonusConfigDetail != null) {
                        oldSkuMap.remove(achievementBonusConfigDetail.getId());
                        BeanUtil.copyProperties(achievementBonusConfigDetailVo, achievementBonusConfigDetail, CopyOptions.create().setIgnoreNullValue(true));
                        achievementBonusConfigDetailMapper.updateById(achievementBonusConfigDetail);
                    }
                }
            }
        }
        if(CollectionUtil.isNotEmpty(oldSkuMap)){
            for (Long aLong : oldSkuMap.keySet()) {
                achievementBonusConfigDetailMapper.deleteById(aLong);
            }
        }
    }

    @Override
    public List<AchievementBonusConfigVo> getAchievementConfigList(AchievementBonusConfigVo vo) {
        List<AchievementBonusConfigVo> result = new ArrayList<>();
        Map<String,Object> param = new HashMap<>();
        param.put("deleted",0);
        List<AchievementBonusConfig> achievementBonusConfigs = achievementBonusConfigMapper.selectByMap(param);
        if(CollectionUtil.isEmpty(achievementBonusConfigs)){
            return result;
        }
        for (AchievementBonusConfig achievementBonusConfig : achievementBonusConfigs) {
            AchievementBonusConfigVo configVo = new AchievementBonusConfigVo();
            BeanUtil.copyProperties(achievementBonusConfig,configVo, CopyOptions.create().setIgnoreNullValue(true));
            result.add(configVo);
            param.clear();
            param.put("deleted",0);
            param.put("config_id",achievementBonusConfig.getId());
            List<AchievementBonusConfigDetail> achievementBonusConfigDetailList = achievementBonusConfigDetailMapper.selectByMap(param);
            List<AchievementBonusConfigDetailVo> detailVoList = new ArrayList<>();
            if(!CollectionUtil.isEmpty(achievementBonusConfigDetailList)){
                for (AchievementBonusConfigDetail achievementBonusConfigDetail : achievementBonusConfigDetailList) {
                    AchievementBonusConfigDetailVo detailVo = new AchievementBonusConfigDetailVo();
                    BeanUtil.copyProperties(achievementBonusConfigDetail,detailVo, CopyOptions.create().setIgnoreNullValue(true));
                    detailVoList.add(detailVo);
                }
            }
            configVo.setConfigDetailList(detailVoList);
        }
        return result;
    }

    /**
     * c插队核心处理方法
     * @param distributionTwoLevelCount
     */
    private void jumpToQueue(DistributionTwoLevelCount distributionTwoLevelCount){
        SysConfig config = new SysConfig();
        config.setConfigKey(Constant.CONFIG_KEY_DISTRIBUTION_UPGRADE_LIMIT);
        config = sysConfigMapper.selectOne(config);
        String configValue = config.getConfigValue();
        int limit = Integer.valueOf(configValue);
        Integer num = distributionTwoLevelCount.getNum();
        if(num >= limit){
            long orderId = -1;
            Long userId = distributionTwoLevelCount.getUserId();
            DistributionOrder distributionOrder = distributionOrderMapper.getNeedUpdateOrderOne(userId);
            if(distributionOrder!=null){
                //获取需要插队的订单 优先级为 商品级别由高到低 结算时间由低到高
                distributionOrder.setVipOrders(1);
                distributionOrder.setVipTime(new Date());
                distributionOrderMapper.updateById(distributionOrder);
                //对队列进行VIP排序
                DistributionOrderQueue qu = new DistributionOrderQueue();
                qu.setDistributionOrderId(distributionOrder.getId());
                DistributionOrderQueue distributionOrderQueue = distributionOrderQueueMapper.selectOne(qu);
                distributionOrderQueue.setSort(IdUtil.generateId());
                distributionOrderQueue.setRealSort(DistributionOrderQueue.getQueueSort(1,distributionOrderQueue.getBonusPresentation(),distributionOrderQueue.getSort()));
                distributionOrderQueueMapper.updateById(distributionOrderQueue);
                orderId = distributionOrder.getId();
            }
            DistributionTwoLevelHelpRecord helpRecord = new DistributionTwoLevelHelpRecord();
            helpRecord.setCreateTime(new Date());
            helpRecord.setId(IdUtil.generateId());
            helpRecord.setOrderId(orderId);
            helpRecord.setUserId(userId);
            helpRecord.setTwoLevelCountId(distributionTwoLevelCount.getId());
            distributionTwoLevelHelpRecordMapper.insert(helpRecord);
            //更新 DistributionTwoLevelCountRecord 订单ID
            distributionTwoLevelCountRecordMapper.updateOrderIdByLimit(distributionTwoLevelCount.getId(),orderId,limit);
            distributionTwoLevelCount.setNum(0);
            distributionTwoLevelCountMapper.updateById(distributionTwoLevelCount);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //分销复投现成
        String[] flags = {Constant.ZHONG_JI_DISTRIBUTION_FLAG, Constant.GAO_JI_DISTRIBUTION_FLAG,
                Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG};
        new Thread(()->{
            while(true){
                if(!taskSwith){
                    continue;
                }
                task(flags);
                boolean isContinu = false;
                try{
                    //查看是否还有需要复投的订单
                    for (String levelFlag : flags) {
                        List<DistributionGoods> distributionGoodsByFLag = distributionGoodsMapper.getDistributionGoodsByFLag(Arrays.asList(new String[]{levelFlag}));
                        if(!CollectionUtils.isEmpty(distributionGoodsByFLag)){
                            DistributionGoods distributionGoods = distributionGoodsByFLag.get(0);
                            BigDecimal promotedPresentationLimit = distributionGoods.getPromotedPresentationLimit();
                            DistributionOrderQueueVo order = distributionOrderQueueMapper.getFirstOrder(levelFlag,null);
                            isContinu = order!=null && order.getBonusPresentation().compareTo(promotedPresentationLimit)>=0;
                            if(isContinu){
                                break;
                            }
                        }
                    }
                }catch (Exception e){
                    log.error("DistributionServiceImpl afterPropertiesSet task",e);
                }
                try{
                    if(!isContinu){
                        Thread.sleep(60000L);
                    }
                }catch (Exception e){
                    log.error("DistributionServiceImpl afterPropertiesSet sleep",e);
                }
            }
        }).start();
    }

    /**
     * 分销复投任务方法
     * 三期:分红订单不参与订单排队
     * @param flags
     */
    private void task(String[] flags){
        for (String levelFlag : flags) {
            try{
                //将分红助益给排名第一的人
                //获取排名第一的订单
                DistributionOrderQueueVo order = distributionOrderQueueMapper.getFirstOrder(levelFlag,null);
                if(order == null){
                    continue;
                }
                List<DistributionGoods> distributionGoodsByFLag = distributionGoodsMapper.getDistributionGoodsByFLag(Arrays.asList(new String[]{levelFlag}));
                if(!CollectionUtils.isEmpty(distributionGoodsByFLag)){
                    DistributionGoods distributionGoods = distributionGoodsByFLag.get(0);
                    BigDecimal bonusPresentationOrder = order.getBonusPresentation();
                    BigDecimal promotedPresentationLimit = distributionGoods.getPromotedPresentationLimit();
                    //升级到的级别
                    String updateLevelFlag = null;
                    if(bonusPresentationOrder.compareTo(promotedPresentationLimit)>=0){
                        //如果此订单分红金额足以晋升,则进行晋升
                        List<DistributionGoods> bayList = null;
                        Integer buyType = null;
                        Long distributionOrderId = order.getDistributionOrderId();
                        DistributionOrder distributionOrder = distributionOrderMapper.selectById(distributionOrderId);
                        if(levelFlag.equalsIgnoreCase(Constant.ZHONG_JI_DISTRIBUTION_FLAG)){
                            //如果是中级升高级
                            //总分红 购买一个高级  剩下为受益
                            bayList = distributionGoodsMapper.getDistributionGoodsByFLag(Arrays.asList(new String[]{Constant.GAO_JI_DISTRIBUTION_FLAG
                                    ,Constant.ZHONG_JI_DISTRIBUTION_FLAG}));
                            buyType = DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_3.getCn();
                            updateLevelFlag = Constant.GAO_JI_DISTRIBUTION_FLAG;
                        }else if(levelFlag.equalsIgnoreCase(Constant.GAO_JI_DISTRIBUTION_FLAG)){
                            //如果是高级晋级到超高级
                            //总分红以金钱购买价格 购买一个超高级 高级  中级  初级   剩下为受益
                            bayList = distributionGoodsMapper.getDistributionGoodsByFLag(Arrays.asList(new String[]{Constant.GAO_JI_DISTRIBUTION_FLAG
                                    ,Constant.ZHONG_JI_DISTRIBUTION_FLAG,Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG}));
                            buyType = DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_7.getCn();
                            updateLevelFlag = Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG;
                        }else if(levelFlag.equalsIgnoreCase(Constant.CHAO_GAO_JI_DISTRIBUTION_FLAG)){
                            //超高级队列不晋升 用金钱价格购买
                            //总分红以金钱购买价格 购买一个高级  剩下为受益
                           //超高级取消复投
                            bayList = distributionGoodsMapper.getDistributionGoodsByFLag(
                                    Arrays.asList(new String[]{Constant.ZHONG_JI_DISTRIBUTION_FLAG}));
                            buyType = DistriButionPayTypeDict.DISTRIBUTION_PAY_TYPE_4.getCn();
                            //将超高级关单
                            distributionOrder.setOrderStatus(DistributionStatusDict.ORDER_STATUS_CLOSE.getCn());
                            distributionOrderMapper.updateById(distributionOrder);
                            order.setBonusPresentation(BigDecimal.ZERO);
                            DistributionOrderQueue orderQueue = new DistributionOrderQueue();
                            BeanUtil.copyProperties(order,orderQueue);
                            distributionOrderQueueMapper.updateById(orderQueue);
                        }
                        //进行晋级购买
                        if(!CollectionUtils.isEmpty(bayList)){
                            List<Long> buyOrderIdList = new ArrayList<>();
                            Boolean isUpdate = null;
                            for (DistributionGoods goods : bayList) {
                                String levelFlaggoods = goods.getLevelFlag();
                                Long orderId = null;
                                isUpdate = updateLevelFlag!=null && updateLevelFlag.equalsIgnoreCase(levelFlaggoods);
                                if(isUpdate){
                                    //升级
                                    orderId = order.getDistributionOrderId();
                                    order.setLevelFlag(updateLevelFlag);
                                    order.setDistributionGoodsId(goods.getId());
                                    order.setBonusPresentation(BigDecimal.ZERO);
                                    DistributionOrderQueue orderQueue = new DistributionOrderQueue();
                                    BeanUtil.copyProperties(order,orderQueue);
                                    orderQueue.setSort(IdUtil.generateId());
                                    orderQueue.setRealSort(DistributionOrderQueue.getQueueSort(distributionOrder.getVipOrders(),orderQueue.getBonusPresentation(),orderQueue.getSort()));
                                    distributionOrderQueueMapper.updateById(orderQueue);
                                    DistributionOrderQueueGoods queueGoods = new DistributionOrderQueueGoods();
                                    BeanUtil.copyProperties(goods,queueGoods);
                                    queueGoods.setOrderId(orderId);
                                    queueGoods.setCreateTime(new Date());
                                    queueGoods.setUpdateTime(new Date());
                                    //针对积分和分红的处理
                                    //因为是升级所以积分为0
                                    queueGoods.setBonusPoints(BigDecimal.ZERO);
                                    distributionOrderQueueGoodsMapper.insert(queueGoods);
                                }else{
                                    //助益
                                    DistributionOrderVo vo = new DistributionOrderVo();
                                    vo.setDistributionGoodsId(goods.getId());
                                    vo.setPayType(buyType);
                                    vo.setUserId(order.getUserId());
                                    vo.setPId(order.getDistributionOrderId());
                                    vo.setOrderType(DistriButionOrderTypeDict.DISTRIBUTION_PAY_TYPE_0.getCn());
                                    DistributionOrderVo distributionOrderVo = addDistributionOrder(vo,false);
                                    orderId = distributionOrderVo.getId();
                                }
                                buyOrderIdList.add(orderId);
                                BigDecimal price = null;
                                if(DistriButionPayTypeDict.checkFhType(buyType)){
                                    //如果是分红否买
                                    price = goods.getPromotedPresentationAdd();
                                }else{
                                    price = goods.getPrice();
                                }
                                bonusPresentationOrder = DecimalUtil.subArrayOriginalValue(bonusPresentationOrder,price);
                                DistributionBonusUserRecord record = new DistributionBonusUserRecord();
                                record.setOrderId(order.getDistributionOrderId());
                                record.setLevelFlag(levelFlag);
                                record.setBonusPresentation(price);
                                record.setCreateTime(new Date());
                                record.setUseOrderId(orderId);
                                record.setDes(isUpdate?"升级":"复投"+goods.getDistributionName());
                                record.setType(isUpdate
                                        ?DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_5.getCn():DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_4.getCn());
                                record.setBonusBalance(bonusPresentationOrder);
                                distributionBonusUserRecordMapper.insert(record);
                            }
                            for (Long aLong : buyOrderIdList) {
                                postProcess(aLong,buyType,false,order.getDistributionOrderId().equals(aLong));
                            }
                        }
                        //为队首之人添加收益
                        TUserAccount acc = userAccountService.initUserAccountByUserId(order.getUserId());
                        BigDecimal benefit = acc.getBenefit();
                        benefit = DecimalUtil.addArray(benefit,bonusPresentationOrder);
                        acc.setBenefit(benefit);
                        tUserAccountMapper.updateById(acc);
                        DistributionBonusUserRecord record = new DistributionBonusUserRecord();
                        record.setOrderId(order.getDistributionOrderId());
                        record.setLevelFlag(levelFlag);
                        record.setBonusPresentation(bonusPresentationOrder);
                        record.setCreateTime(new Date());
                        record.setDes("分红转收益");
                        record.setType(DistributionBonusRecordTypeDict.DISTRIBUTION_BONUS_RECORD_TYPE_6.getCn());
                        record.setBonusBalance(BigDecimal.ZERO);
                        distributionBonusUserRecordMapper.insert(record);
                        //添加受益流水
                        BenefitTransaction bt = new BenefitTransaction();
                        bt.setCreateTime(new Date());
                        bt.setType(BenefitTranTypeDict.BENEFIT_TRAN_TYPE_100.getCn());
                        bt.setDes(distributionGoods.getDistributionName()+"拼团收益");
                        bt.setOrderId(order.getDistributionOrderId());
                        bt.setCurrentTotalBenefit(benefit);
                        bt.setBenefit(bonusPresentationOrder);
                        bt.setUserId(order.getUserId());
                        //获取此类型当前收益总额
                        List<Integer> typeList = new ArrayList<>();
                        typeList.add(bt.getType());
                        BigDecimal sumType = benefitTransactionMapper.getSumByTypeList(bt.getUserId(),typeList);
                        bt.setCurrentTypeBenefit(DecimalUtil.addArray(bt.getBenefit(),sumType));
                        benefitTransactionMapper.insert(bt);
                    }
                }

            }catch(Exception e){
                log.error("DistributionServiceImpl afterPropertiesSet levelFlag",levelFlag,e);
            }
        }
    }
}
